输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码:
class Solution {
public int[] spiralOrder(int[][] matrix) {
int m = matrix.length;
if (m == 0) return new int[]{};
int n = matrix[0].length;
//结果数组
int[] res = new int[m * n];
int curr = 0;
//标记对应数字是否已经添加到结果数组中
int[][] flag = new int[m][n];
//方向数组
int[] dx = {-1, 0, 1, 0};
int[] dy = {0, 1, 0, -1};
int d = 1;
//当前点坐标
int x = 0, y = 0;
for (int i = 0; i < m * n; i++) {
res[curr] = matrix[x][y];
flag[x][y] = 1;
curr++;
int a = x + dx[d];
int b = y + dy[d];
//如果按照当前方向继续走会撞墙(越界或者已经走过)
if (a < 0 || a >= m || b < 0 || b >= n || flag[a][b] == 1) {
//拐弯
d = (d + 1) % 4;
a = x + dx[d];
b = y + dy[d];
}
x = a;
y = b;
}
return res;
}
}