剑指 Offer 29. 顺时针打印矩阵
剑指 Offer 29. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
注意:本题与主站 54 题相同:https://leetcode-cn.com/problems/spiral-matrix/
通过次数177,812提交次数405,998
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix.length ==0 )return new int[]{};
int[][] visit = new int [105][105];
int n = matrix.length, m = matrix[0].length;
int[] res = new int[n*m];//存放结果的arr
int[][] dp={{0,1},{1,0},{0,-1},{-1,0}};
int cnt = 0;
int row = 0 , col = 0;
int i = 0 ;//director
while(cnt<n*m)
{
res[cnt++] = matrix[row][col];
visit[row][col] = 1;
int drow = row+dp[i][0],dcol = col + dp[i][1];
if(drow<0||drow>=n||dcol<0||dcol>=m||visit[drow][dcol]==1)
{
i = (i+1)%4;
}
row = row+dp[i][0];
col = col + dp[i][1];
}
//123
//456
//789
return res;
}
}