Created
February 17, 2013 11:20
-
-
Save pdu/4971046 to your computer and use it in GitHub Desktop.
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 ]
] http://leetcode.com/onlinejudge#question_59
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int dir[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; | |
| bool inBound(int x, int y, int n) { | |
| return x >= 0 && x < n && y >= 0 && y < n; | |
| } | |
| class Solution { | |
| public: | |
| vector<vector<int> > generateMatrix(int n) { | |
| vector<vector<int> > ans; | |
| if (n == 0) | |
| return ans; | |
| ans.resize(n); | |
| for (int i = 0; i < n; ++i) { | |
| ans[i].resize(n); | |
| for (int j = 0; j < n; ++j) | |
| ans[i][j] = 0; | |
| } | |
| int x = 0, y = 0; | |
| int d = 0; | |
| ans[x][y] = 1; | |
| for (int val = 2; val <= n * n; val++) { | |
| while (true) { | |
| int nx = x + dir[d][0], ny = y + dir[d][1]; | |
| if (inBound(nx, ny, n) && ans[nx][ny] == 0) { | |
| ans[nx][ny] = val; | |
| x = nx; | |
| y = ny; | |
| break; | |
| } | |
| d = (d + 1) % 4; | |
| } | |
| } | |
| return ans; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment