Spiral Matrix
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]
.
解题思路:
求一个矩阵循环绕矩形输出元素。我们可以利用矩阵四条边的规则输出各个元素。左上---右上,右上---右下,右下---左下,左下---左上,按此顺序输出矩形的四条边,矩形由小到大,直到输出所有元素为止。代码如下:
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; if(matrix.size()==0) return res; int n=matrix.size(); int m=matrix[0].size(); for (int row=0;row<n/2+1;row++) { int i=row; int j=i; for (j=i;j<(m-row);j++) { res.push_back(matrix[i][j]); if (res.size()==(n*m)) { return res; } } j--; for (i=row+1;i<(n-row);i++) { res.push_back(matrix[i][j]); if (res.size()==(n*m)) { return res; } } i--; for (j=j-1;j>=row;j--) { res.push_back(matrix[i][j]); if (res.size()==(n*m)) { return res; } } j++; for (i=i-1;i>=row+1;i--) { res.push_back(matrix[i][j]); if (res.size()==(n*m)) { return res; } } } return res; } };
Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution { public: vector<vector<int>> generateMatrix(int n) { int x=0; vector<vector<int>> res; vector<int> temp(n,0); for (int i=0;i<n;i++) { res.push_back(temp); } for (int row=0;row<n/2+1;row++) { int i=row; int j=i; for (j=i;j<(n-row);j++)//左---右 { res[i][j]=++x; } j--; for (i=row+1;i<(n-row);i++)//上---下 { res[i][j]=++x; } i--; for (j=j-1;j>=row;j--)//右---左 { res[i][j]=++x; } j++; for (i=i-1;i>=row+1;i--)//下---上 { res[i][j]=++x; } } return res; } };
时间: 2024-10-27 18:59:34