54. 螺旋矩阵/面试题29. 顺时针打印矩阵(一般) 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1: 1 2 3 4 5 6 7 输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]
示例 2: 1 2 3 4 5 6 7 输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/spiral-matrix
思路: 按照右,下,左,上的顺序读,每次计数num-1,直到减完,值得多看多学
思路3 深搜
代码1: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 class Solution { public List<Integer> spiralOrder (int [][] matrix) { List<Integer> aList = new ArrayList<Integer>(); if (matrix.length == 0 ||matrix == null) return aList; int m = matrix.length; int n = matrix[0 ].length; int l=0 ,r=n-1 ; int t=0 ,b=m-1 ; int num=m*n; while (num>0 ){ for (int j=l;j<=r;j++){ aList.add(matrix[t][j]); num--; } if (num<=0 ) return aList; t++; for (int i=t;i<=b;i++){ aList.add(matrix[i][r]); num--; } if (num<=0 ) return aList; r--; for (int j=r;j>=l;j--){ aList.add(matrix[b][j]); num--; } if (num<=0 ) return aList; b--; for (int i=b;i>=t;i--){ aList.add(matrix[i][l]); num--; } if (num<=0 ) return aList; l++; } return aList; } }
代码2: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 class Solution { public int [] spiralOrder(int [][] matrix) { if (matrix.length == 0 ||matrix == null ) return new int [0 ]; int m = matrix.length; int n = matrix[0 ].length; int [] res = new int [m * n]; int count=0 ; int l=0 ,r=n-1 ; int t=0 ,b=m-1 ; int num=m*n; while (num>0 ){ for (int j=l;j<=r;j++){ res[count++]=matrix[t][j]; num--; } if (num<=0 ) break ; t++; for (int i=t;i<=b;i++){ res[count++]=matrix[i][r]; num--; } if (num<=0 ) break ; r--; for (int j=r;j>=l;j--){ res[count++] = matrix[b][j]; num--; } if (num<=0 ) break ; b--; for (int i=b;i>=t;i--){ res[count++] = matrix[i][l]; num--; } if (num<=0 ) break ; l++; } return res; } }
代码3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 class Solution { List<Integer> res = new ArrayList<>(); public List<Integer> spiralOrder (int [][] matrix) { if (matrix==null || matrix.length==0 ){ return res; } boolean [][] isVisited = new boolean [matrix.length][matrix[0 ].length]; dfs(matrix,isVisited,0 ,0 ); return res; } public void dfs (int [][] matrix,boolean [][] isVisited,int m,int n) { int row = matrix.length-1 ,col = matrix[0 ].length-1 ; if (m<0 || m>row || n<0 || n>col || isVisited[m][n]){ return ; } res.add(matrix[m][n]); isVisited[m][n] = true ; if (n-1 <0 || isVisited[m][n-1 ]){ dfs(matrix,isVisited,m-1 ,n); } dfs(matrix,isVisited,m,n+1 ); dfs(matrix,isVisited,m+1 ,n); dfs(matrix,isVisited,m,n-1 ); dfs(matrix,isVisited,m-1 ,n); } }