Easy to understand Java code


  • 1
    S
    public List<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0) return list;
        int n = matrix.length;
        int m = matrix[0].length;
        int direction = 0;//0,1,2,3分别表示右,↓,←,↑
        int[][] flag = new int[n][m];//用于标示是否访问过
        int k = 0;
        int i = 0, j = 0;
        list.add(matrix[i][j]);
        k++;
        flag[i][j] = 1;
        while (k < m*n){
            if (direction == 0){
                while (j+1 < matrix[i].length && flag[i][j+1] == 0){
                    j = j+1;
                    list.add(matrix[i][j]);
                    k++;
                    flag[i][j] = 1;
                }
                direction = 1;
            }
            if (direction == 1){
                while (i+1 < matrix.length && flag[i+1][j] == 0){
                    i = i+1;
                    list.add(matrix[i][j]);
                    k++;
                    flag[i][j] = 1;
                }
                direction = 2;
            }
            if (direction == 2){
                while (j-1 >= 0 && flag[i][j-1] == 0){
                    j = j-1;
                    list.add(matrix[i][j]);
                    k++;
                    flag[i][j] = 1;
                }
                direction = 3;
            }
            if (direction == 3){
                while (i-1 >= 0 && flag[i-1][j] == 0){
                    i = i-1;
                    list.add(matrix[i][j]);
                    k++;
                    flag[i][j] = 1;
                }
                direction = 0;
            }
        }
        return list;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.