zoukankan      html  css  js  c++  java
  • LeetCode-054-螺旋矩阵

    螺旋矩阵

    题目描述:给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

    示例说明请见LeetCode官网。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/spiral-matrix/
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解法一:数组遍历

    首先,用row和column分别记录matrix的行数和列数,count为matrix所有的元素数量,初始化一个数量和matrix一样的二维数组用来标记相应位置的数字是否已经遍历到,初始化result记录结果的顺序,x和y记录当前位置的索引位置,然后按照向右、向下、向左、向右的顺序开始处理二维数组:

    • 向右:将y往右移动一位,判断是否超过column的界限并且移动后的位置是否没有遍历过,如果符合条件,则将移动后的位置的值放入result中,并且将count减一,并且将该位置的标记位置为true,直到往右移不动为止;
    • 向下:将x往下移动一位,判断是否超过row的界限并且移动后的位置是否没有遍历过,如果符合条件,则将移动后的位置的值放入result中,并且将count减一,并且将该位置的标记位置为true,直到往下移不动为止;
    • 往左:将y往左移动一位,判断是否不小于0并且移动后的位置是否没有遍历过,如果符合条件,则将移动后的位置的值放入result中,并且将count减一,并且将该位置的标记位置为true,直到往左移不动为止;
    • 往上:将上往左移动一位,判断是否不小于0并且移动后的位置是否没有遍历过,如果符合条件,则将移动后的位置的值放入result中,并且将count减一,并且将该位置的标记位置为true,直到往上移不动为止。

    重复上面的过程,知道count为0即所有的数字都遍历到为止,返回result。

    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 + " ");
            }
        }
    }
    

    【每日寄语】 愿你今天温柔,优秀,可爱,果断,一尘不染。

  • 相关阅读:
    hdu 5101 Select
    hdu 5100 Chessboard
    cf B. I.O.U.
    cf C. Inna and Dima
    cf B. Inna and Nine
    cf C. Counting Kangaroos is Fun
    Radar Installation 贪心
    spfa模板
    Sequence
    棋盘问题
  • 原文地址:https://www.cnblogs.com/kaesar/p/15126636.html
Copyright © 2011-2022 走看看