您的位置:首页 > 其它

LeetCode 59: Spiral Matrix II

2013-09-02 13:52 309 查看
Difficulty: 3

Frequency: 2

Problem:

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

Solution:

class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> row(n,0);
vector<vector<int> > matrix;
for (int i = 0; i<n; i++)
matrix.push_back(row);

char next_move = 0;
int i_row = 0, i_col = 0;
for (int i = 1; i<=n*n; i++)
{
matrix[i_row][i_col] = i;
switch(next_move){
case 0:
if (i_col==n-1||matrix[i_row][i_col+1]!=0)
{
++i_row;
next_move = (next_move+1)%4;
}
else
++i_col;
break;
case 1:
if (i_row==n-1||matrix[i_row+1][i_col]!=0)
{
--i_col;
next_move = (next_move+1)%4;
}
else
++i_row;
break;
case 2:
if (i_col==0||matrix[i_row][i_col-1]!=0)
{
--i_row;
next_move = (next_move+1)%4;
}
else
--i_col;
break;
case 3:
if (i_row==0||matrix[i_row-1][i_col]!=0)
{
++i_col;
next_move = (next_move+1)%4;
}
else
--i_row;
break;
}
}
return matrix;
}
};

Notes:

Don't know if there is a mathematical formula about this problem.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: