题目一: 转圈遍历一个矩阵
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]
.
思路:使用start X,end X,start Y,end Y来记录当前遍历到的区域 。需要注意到到点是,当中心只剩下一行或者一列或一个元素的时候,需要进行特殊处理。
vector<int> spiralOrder(vector<vector<int> > matrix){
vector<int> result;
if(matrix.size() == 0){
return result;
}
int startX, startY, endX, endY;
startX = 0;
startY = 0;
endY = matrix.size()-1;
endX = matrix[0].size()-1;
while(startX < endX && startY < endY){
for(int i=startX; i<endX; i++){
result.push_back(matrix[startY][i]);
}
for(int i=startY; i<endY; i++){
result.push_back(matrix[i][endX]);
}
for(int i=endX; i>startX; i--){
result.push_back(matrix[endY][i]);
}
for(int i=endY; i>startY; i--){
result.push_back(matrix[i][startX]);
}
startX++;
startY++;
endX--;
endY--;
}
if(startX == endX && startY == endY){
result.push_back(matrix[startX][startY]);
}
if(startX == endX && startY < endY){
for(int i=startY; i<=endY; i++){
result.push_back(matrix[i][startX]);
}
}
if(startY == endY && startX < endX){
for(int i=startX; i<=endX; i++){
result.push_back(matrix[startY][i]);
}
}
return result;
}
题目二:创建一个矩阵
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 ] ]
思路:过程与题一中基本相同,先创建好矩阵,然后仍然按照题一中点方式,遍历填入值
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > result;
for(int i=0; i<n; i++){
vector<int> temp(n, 0);
result.push_back(temp);
}
int startX, endX, startY, endY, count;
startX = 0;
startY = 0;
endX = n-1;
endY = n-1;
count = 1;
while(startX < endX && startY < endY){
for(int i=startX; i<endX; i++){
result[startY][i] = count++;
}
for(int i=startY; i<endY; i++){
result[i][endX] = count++;
}
for(int i=endX; i>startX; i--){
result[endY][i] = count++;
}
for(int i=endY; i>startY; i--){
result[i][startX] = count++;
}
startX++;
startY++;
endX--;
endY--;
}
if(startX == endX && startY == endY){
result[startX][startY] = count++;
}
if(startX == endX && startY < endY){
for(int i=startY; i<=endY; i++){
result[i][startX] = count++;
}
}
if(startY == endY && startX < endX){
for(int i=startX; i<=endX; i++){
result[startY][i] = count++;
}
}
return result;
}