leetcode54-螺旋矩阵

螺旋矩阵

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int m = matrix.length, n = matrix[0].length, i = 0, j = 0, cnt = 0;
        list.add(matrix[0][0]);
        matrix[0][0] = Integer.MIN_VALUE;
        while(cnt < m*n-1){
            while(j+1 < n && matrix[i][j+1] != Integer.MIN_VALUE){
                j++;
                cnt++;
                list.add(matrix[i][j]);
                matrix[i][j] = Integer.MIN_VALUE;
            }
            while(i+1 < m && matrix[i+1][j] != Integer.MIN_VALUE){
                i++;
                cnt++;
                list.add(matrix[i][j]);
                matrix[i][j] = Integer.MIN_VALUE;
            }
            while(j-1 >= 0 && matrix[i][j-1] != Integer.MIN_VALUE){
                j--;
                cnt++;
                list.add(matrix[i][j]);
                matrix[i][j] = Integer.MIN_VALUE;
            }
            while(i-1 >= 0 && matrix[i-1][j] != Integer.MIN_VALUE){
                i--;
                cnt++;
                list.add(matrix[i][j]);
                matrix[i][j] = Integer.MIN_VALUE;
            }
        }
        return list;
    }
}
posted @ 2022-08-22 22:57  xzh-yyds  阅读(20)  评论(0)    收藏  举报