Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5].
题目链接:https://leetcode.com/problems/spiral-matrix/
题目分析:模拟填数过程即可
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
int n = matrix.length;
if (n == 0) {
return ans;
}
int m = matrix[0].length;
int all = n * m, cnt = 0, i = 0, j = 0;
boolean[][] vis = new boolean[n + 1][m + 1];
while (cnt < all) {
while (j < m && !vis[i][j]) {
vis[i][j] = true;
cnt ++;
ans.add(matrix[i][j ++]);
}
j --;
i ++;
while (i < n && !vis[i][j]) {
vis[i][j] = true;
cnt ++;
ans.add(matrix[i ++][j]);
}
i --;
j --;
while (j >= 0 && !vis[i][j]) {
vis[i][j] = true;
cnt ++;
ans.add(matrix[i][j --]);
}
j ++;
i --;
while (i >= 0 && !vis[i][j]) {
vis[i][j] = true;
cnt ++;
ans.add(matrix[i --][j]);
}
i ++;
j ++;
}
return ans;
}
}
其实不开boolean数组也可以
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
int n = matrix.length;
if (n == 0) {
return ans;
}
int m = matrix[0].length;
int left = 0, right = m - 1, down = n - 1, up = 0;
while (true) {
for (int j = left; j <= right; j ++) {
ans.add(matrix[up][j]);
}
up ++;
if (left > right || up > down) {
break;
}
for (int i = up; i <= down; i ++) {
ans.add(matrix[i][right]);
}
right --;
if (left > right || up > down) {
break;
}
for (int j = right; j >= left; j --) {
ans.add(matrix[down][j]);
}
down --;
if (left > right || up > down) {
break;
}
for (int i = down; i >= up; i --) {
ans.add(matrix[i][left]);
}
left ++;
if (left > right || up > down) {
break;
}
}
return ans;
}
}

本文介绍了一种算法,用于按螺旋顺序遍历二维矩阵的所有元素。通过两种不同的实现方式,展示了如何从左上角开始,顺时针螺旋遍历整个矩阵。
2821

被折叠的 条评论
为什么被折叠?



