54. 螺旋矩阵

发布时间:2024年01月23日

给你一个?m?行?n?列的矩阵?matrix?,请按照?顺时针螺旋顺序?,返回矩阵中的所有元素。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

方法1:(0ms)

    public static List<Integer> spiralOrder(int[][] matrix) {
        int[][] path = new int[matrix.length][matrix[0].length];
        int step = 0;
        ArrayList<Integer> list = new ArrayList<>();
        int row = 0;
        int col = 0;
        int direct = 0;
        while (step < matrix.length * matrix[0].length){
            list.add(matrix[row][col]);
            path[row][col] = 1;
            if (direct == 0){
                col++;
                if (col == matrix[0].length || path[row][col] == 1){
                    direct = 1;
                    col--;
                    row++;
                }
            }else if (direct == 1){
                row++;
                if (row == matrix.length || path[row][col] == 1){
                    direct = 2;
                    row--;
                    col--;
                }
            }else if (direct == 2){
                col--;
                if (col == -1 || path[row][col] == 1){
                    direct = 3;
                    col++;
                    row--;
                }
            }else {
                row--;
                if (row == 0 || path[row][col] == 1){
                    direct = 0;
                    row++;
                    col++;
                }
            }
            step++;
        }
        return list;
    }

方法2:(0ms)

   public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        List<Integer> res = new ArrayList<>();
        int u = 0, d = m - 1, l = 0, r = n - 1;
        while (true) {
            for (int i = l; i <= r; i ++) res.add(matrix[u][i]);
            if (++u > d) break;
            for (int i = u; i <= d; i ++) res.add(matrix[i][r]);
            if (--r < l) break;
            for (int i = r; i >= l; i --) res.add(matrix[d][i]);
            if (--d < u) break;
            for (int i = d; i  >= u; i --) res.add(matrix[i][l]);
            if (++l > r) break;
        }
        return res; 
    }

文章来源:https://blog.csdn.net/linping_wong/article/details/135794914
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。