简介
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解题思路
设置一个二维数组,分别进行以下操作指导填满整个二维数组:
- 由起始列向右填数至终止列,起始行加一
- 由终止列向下填数至终止行,终止列减一
- 由终止列向左填数至起始列,终止行减一
- 由终止行向上填数至起始行,起始列加一
参考代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> vec(n, vector<int>(n));//二维数组
int row_first = 0; //起始行
int col_first = 0; //终止行
int row_last = n; //起始列
int col_last = n; //终止列
int cnt = 0; //待填数
while(cnt < n*n)
{
//向左填数
cout << row_first << " " << row_last << " " << col_first << " " << col_last << endl;
for(int i = col_first; i < col_last; i++)
{
cnt++;
vec[row_first][i] = cnt;
cout << "i=" << i << endl;
cout << "vec[row_first][i]=" << vec[row_first][i] << endl;
}
cout << endl;
row_first++;
//向下填数
cout << row_first << " " << row_last << " " << col_first << " " << col_last << endl;
for(int i = row_first; i < row_last; i++)
{
cnt++;
vec[i][col_last-1] = cnt;
cout << "i=" << i << endl;
cout << "vec[i][col_last-1]=" << vec[i][col_last-1] << endl;
}
cout << endl;
col_last--;
//向右填数
cout << row_first << " " << row_last << " " << col_first << " " << col_last << endl;
for(int i = col_last-1; i >= col_first; i--)
{
cnt++;
vec[row_last-1][i] = cnt;
cout << "i=" << i << endl;
cout << "vec[row_last-1][i]=" << vec[row_last-1][i] << endl;
}
cout << endl;
row_last--;
//向上填数
cout << row_first << " " << row_last << " " << col_first << " " << col_last << endl;
for(int i = row_last-1; i >= row_first; i--)
{
cnt++;
vec[i][col_first] = cnt;
cout << "i=" << i << endl;
cout << "vec[i][col_first]=" << vec[i][col_first] << endl;
}
cout << endl;
col_first++;
}
return vec;
}
};
int main()
{
Solution su;
int n;
cin >> n;
vector<vector<int>> ret = su.generateMatrix(n);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
cout << ret[i][j] << " ";
return 0;
}
总结
申明vector二维数组:vector<vector> vec(n, vector(n))