【leetcode】Spiral Matrix(middle)

时间:2024-04-23 23:38:01

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].

思路:就按照螺旋矩阵的规律 用n记录旋转圈数 每圈按左下右上的顺序取值。 注意去重复。

class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ans;
if(matrix.empty())
return ans;
int M = matrix.size();
int N = matrix[].size(); for(int n = ; n < min((M+)/,(N+)/);n++)
{
//行 ----->
for(int i = n; i < N - n; i++)
ans.push_back(matrix[n][i]);
//列 向下
for(int i = n + ; i < M - n; i++)
ans.push_back(matrix[i][N - - n]);
//行 <-----------
if(M - n - <= n) //列号 一定要比向左时的列号小 防止重复
break;
for(int i = N - n - ; i >= n; i--)
ans.push_back(matrix[M - n - ][i]);
//列 向上
if(n >= N - - n) //行号 一定要比向下时的行号大 防止重复
break;
for(int i = M - n - ; i >= n + ; i--)
ans.push_back(matrix[i][n]);
}
return ans;
}
};

大神思路和我一样,就是用自定义变量来避免重复取行或列。

public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix.length == ) {
return res;
}
int rowBegin = ;
int rowEnd = matrix.length-;
int colBegin = ;
int colEnd = matrix[].length - ; while (rowBegin <= rowEnd && colBegin <= colEnd) {
// Traverse Right
for (int j = colBegin; j <= colEnd; j ++) {
res.add(matrix[rowBegin][j]);
}
rowBegin++; // Traverse Down
for (int j = rowBegin; j <= rowEnd; j ++) {
res.add(matrix[j][colEnd]);
}
colEnd--; if (rowBegin <= rowEnd) {
// Traverse Left
for (int j = colEnd; j >= colBegin; j --) {
res.add(matrix[rowEnd][j]);
}
}
rowEnd--; if (colBegin <= colEnd) {
// Traver Up
for (int j = rowEnd; j >= rowBegin; j --) {
res.add(matrix[j][colBegin]);
}
}
colBegin ++;
} return res;
}
}