给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
方法1:(0ms)
文章来源:https://www.toymoban.com/news/detail-820204.html
public static List<Integer> spiralOrder(int[][] matrix) {
int[][] path = new int[matrix.length][matrix[0].length];
int step = 0;
ArrayList<Integer> list = new ArrayList<>();
int row = 0;
int col = 0;
int direct = 0;
while (step < matrix.length * matrix[0].length){
list.add(matrix[row][col]);
path[row][col] = 1;
if (direct == 0){
col++;
if (col == matrix[0].length || path[row][col] == 1){
direct = 1;
col--;
row++;
}
}else if (direct == 1){
row++;
if (row == matrix.length || path[row][col] == 1){
direct = 2;
row--;
col--;
}
}else if (direct == 2){
col--;
if (col == -1 || path[row][col] == 1){
direct = 3;
col++;
row--;
}
}else {
row--;
if (row == 0 || path[row][col] == 1){
direct = 0;
row++;
col++;
}
}
step++;
}
return list;
}
方法2:(0ms)文章来源地址https://www.toymoban.com/news/detail-820204.html
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
List<Integer> res = new ArrayList<>();
int u = 0, d = m - 1, l = 0, r = n - 1;
while (true) {
for (int i = l; i <= r; i ++) res.add(matrix[u][i]);
if (++u > d) break;
for (int i = u; i <= d; i ++) res.add(matrix[i][r]);
if (--r < l) break;
for (int i = r; i >= l; i --) res.add(matrix[d][i]);
if (--d < u) break;
for (int i = d; i >= u; i --) res.add(matrix[i][l]);
if (++l > r) break;
}
return res;
}
到了这里,关于54. 螺旋矩阵的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!