0
点赞
收藏
分享

微信扫一扫

LeetCode-054-螺旋矩阵

编程练习生J 2021-09-28 阅读 61
LeetCode

螺旋矩阵

解法一:数组遍历
import java.util.ArrayList;
import java.util.List;

public class LeetCode_054 {
    public static List<Integer> spiralOrder(int[][] matrix) {
        int row = matrix.length, column = matrix[0].length, count = row * column, x = 0, y = -1;
        boolean[][] flag = new boolean[row][column];
        List<Integer> result = new ArrayList<>();
        while (count > 0) {
            // 向右
            while (y + 1 < column && !flag[x][y + 1]) {
                y = y + 1;
                result.add(matrix[x][y]);
                flag[x][y] = true;
                count--;
            }

            // 向下
            while (x + 1 < row && !flag[x + 1][y]) {
                x = x + 1;
                result.add(matrix[x][y]);
                flag[x][y] = true;
                count--;
            }

            // 向左
            while (y - 1 >= 0 && !flag[x][y - 1]) {
                y = y - 1;
                result.add(matrix[x][y]);
                flag[x][y] = true;
                count--;
            }

            // 向上
            while (x - 1 >= 0 && !flag[x - 1][y]) {
                x = x - 1;
                result.add(matrix[x][y]);
                flag[x][y] = true;
                count--;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        for (Integer integer : spiralOrder(matrix)) {
            System.out.print(integer + " ");
        }
    }
}
举报

相关推荐

0 条评论