标签:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]题意:将1到n^2的数依次填写进去。
思路:和上一道回旋的类似做法。
class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > ans; for (int i = 0; i < n; i++) { vector<int> t = vector<int>(n, -1); ans.push_back(t); } int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int dir = 0, x = 0, y = 0; for (int i = 1; i <= n*n; i++) { ans[x][y] = i; if (x+dx[dir] == n || x+dx[dir] < 0 || y+dy[dir] == n || y+dy[dir] < 0 || ans[x+dx[dir]][y+dy[dir]] != -1) { dir = dir == 3 ? 0 : dir + 1; } x += dx[dir]; y += dy[dir]; } return ans; } };
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/44514905