Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].



如果按照直接的思路去做,估計會有一大堆噁心的if、else來判斷邊界條件,所以用一個變形的dfs來做,每次標記一個dfs的方向,先按照這個方向去找,如果找到頭,再找下一個方向。

比如根據題目要求,向右查找的後繼方向應該是向下,像左查找的後繼方向應該是向上等等。


public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(matrix==null||matrix.length==0||matrix[0].length==0){
            return result;
        }
        boolean [][]flags = new boolean[matrix.length][matrix[0].length];
        dfs(matrix,flags,result,0,0,1);
        return result;
    }
      
    public void dfs(int[][] matrix, boolean [][] flags, ArrayList<Integer> result, int i, int j, int direction){
        if(i<0||j<0||i>=matrix.length||j>=matrix[0].length||flags[i][j]){
            return;
        }
        result.add(matrix[i][j]);
        flags[i][j] = true;
          
        switch(direction){
            case 1://right
                dfs(matrix,flags,result,i,j+1,1);
                dfs(matrix,flags,result,i+1,j,2);
                break;
            case 2://down
                dfs(matrix,flags,result,i+1,j,2);
                dfs(matrix,flags,result,i,j-1,3);
                break;
            case 3: // left
                dfs(matrix,flags,result,i,j-1,3);
                dfs(matrix,flags,result,i-1,j,4);
                break;
            case 4:
                dfs(matrix,flags,result,i-1,j,4);
                dfs(matrix,flags,result,i,j+1,1);
                break;
                              
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章