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

1. 对最上一行遍历之后，up++
2. 对最右边一列遍历之后，right–
3. 对最下一行遍历之后，down–
4. 对最左列进行遍历后，left++

class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty())
return {};
int row=matrix.size(),col=matrix[0].size();
int up=0,down=row-1,left=0,right=col-1,k=0,i=0;
vector<int> res(row*col);
while(1){
for(i=left;i<=right;i++)
res[k++]=matrix[up][i];
if(++up>down)
break;

for(i=up;i<=down;i++)
res[k++]=matrix[i][right];
if(--right<left)
break;

for(i=right;i>=left;i--)
res[k++]=matrix[down][i];
if(--down<up)
break;

for(i=down;i>=up;i--)
res[k++]=matrix[i][left];
if(++left>right)
break;
}
return res;
}
};



# 59. 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) {
if(!n)
return {};
vector<vector<int>> res(n,vector<int>(n, 0));/*初始化的时候要仔细考虑，第一次submission因为初始化导致了RTE*/
int up=0,down=n-1,left=0,right=n-1,i=0,j=0,k=0,num=1;
while(true){
for(k=left;k<=right;k++){
res[up][k]=num;
num+=1;
}
if(++up>down)
break;
for(k=up;k<=down;k++){
res[k][right]=num;
num+=1;
}
if(--right<left)
break;
for(k=right;k>=left;k--){
res[down][k]=num;
num+=1;
}
if(--down<up)
break;
for(k=down;k>=up;k--){
res[k][left]=num;
num+=1;
}
if(++left>right)
break;
}
return res;
}
};


### 学籍管理系统文档

#### 北邮教务系统评教脚本

Published on September 17, 2017

#### 72.Edit distance

Published on September 17, 2017