leetcode-螺旋矩阵

可紊 提交于 2020-01-25 07:57:05
class Solution {
    private List<Integer> retlist = new LinkedList<>();
    private int rowlength;
    private int columnlength;

    public List<Integer> spiralOrder(int[][] matrix) {
        if(matrix.length==0){
            return this.retlist;
        }
        this.rowlength = matrix.length;
        this.columnlength = matrix[0].length;
        int index = 0;
        int maxcount = matrix[0].length*matrix.length;
        this.dfs(0,0,matrix,1,maxcount,0);
        return this.retlist;
    }
    public void dfs(int row,int column,int[][] matrix,int order,int maxcount,int index){
        this.retlist.add(matrix[row][column]);
        index+=1;
        if(maxcount==index){
            return;
        }
        //接下来判断方向
        //1是右,2是左,3是上,4是下
        if(order==1){
            if(column+1+row<columnlength){
                this.dfs(row,column+1,matrix,order,maxcount,index);
            }
            else{
                this.dfs(row+1,column,matrix,4,maxcount,index);
            }
        }
        if(order==4){
            if(columnlength-column+row<rowlength){
                this.dfs(row+1,column,matrix,4,maxcount,index);

            }
            else{
                this.dfs(row,column-1,matrix,2,maxcount,index);
            }
        }
        if(order==2){
            if(column>rowlength-row-1){
                this.dfs(row,column-1,matrix,2,maxcount,index);
            }
            else{
                this.dfs(row-1,column,matrix,3,maxcount,index);
            }
        }
        if(order==3){
            if(row-1>=column+1){
                this.dfs(row-1,column,matrix,3,maxcount,index);
            }
            else{
                this.dfs(row,column+1,matrix,1,maxcount,index);
            }
        }
    }
}

这道题的关键就是确定边界转折点,其实这类边界的确定可以这样想。先把当前的row和column写出来,然后找和相应的rowlength,columnlength的关系即可

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!