Link: https://leetcode.com/problems/spiral-matrix/
Solution 1:
记录matrix已经走过的row和col并进行标记
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int rowBegin = 0, rowEnd = matrix.length-1, colBegin = 0, colEnd = matrix[0].length-1;
while(rowBegin <= rowEnd && colBegin <= colEnd) {
for(int i=colBegin; i<=colEnd; i++){ // right
res.add(matrix[rowBegin][i]);
}
rowBegin++;
for(int i=rowBegin; i<=rowEnd; i++) { // down
res.add(matrix[i][colEnd]);
}
colEnd--;
if(rowBegin <= rowEnd && colBegin <= colEnd) { //重要,否则会存在begin已经超过end的情况
for(int i=colEnd; i>=colBegin; i--) { // left
res.add(matrix[rowEnd][i]);
}
rowEnd--;
}
if(rowBegin <= rowEnd && colBegin <= colEnd) { //重要,否则会存在begin已经超过end的情况
for(int i=rowEnd; i>=rowBegin; i--) { // up
res.add(matrix[i][colBegin]);
}
colBegin++;
}
}
return res;
}
}
TC: O(M*N)
SC: O(n)
reference: https://www.youtube.com/watch?v=3joo9yAZVh8&t=3s
Solution 2:
利用坐标控制数字的行动方向
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int R = matrix.length, C = matrix[0].length;
boolean[][] seen = new boolean[R][C];
// row和col的行动方向控制
int row[] = {0, 1, 0, -1};
int col[] = {1, 0, -1, 0};
int r = 0, c = 0, di = 0;
for(int i=0; i<R*C; i++) {
res.add(matrix[r][c]);
seen[r][c] = true;
// 此处暂存r和c,等判断该位置没有超出矩阵边界/到达矩阵拐点
// 则可以加入结果中,否则就拐
int tr = r + row[di];
int tc = c + col[di];
if(tr>=0 && tr<R && tc>=0 && tc<C && !seen[tr][tc]) {
r = tr;
c = tc;
}else{
di = (di+1)%4;
r = r + row[di];
c = c + col[di];
}
}
return res;
}
}