LeetCode: Spiral Matrix II

一次过

 1 class Solution {

 2 public:

 3     bool out(int x, int y, int n) {

 4         if (x >= n || x < 0 || y >= n || y < 0) return true;

 5             return false;

 6     }

 7     void dfs(int x, int y, vector<vector<int>> &ret, int dir[4][2], int dep, int n, int direct) {

 8         if (dep == n*n) return;

 9         ret[x][y] = dep+1;

10         if (out(x+dir[direct][0], y+dir[direct][1], n) || ret[x+dir[direct][0]][y+dir[direct][1]])

11             direct = (direct+1)%4;

12         dfs(x+dir[direct][0], y+dir[direct][1], ret, dir, dep+1, n, direct);

13     }

14     vector<vector<int> > generateMatrix(int n) {

15         // Start typing your C/C++ solution below

16         // DO NOT write int main() function

17         vector<vector<int>> ret(n, vector<int>(n, 0));

18         if (!n) return ret;

19         int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

20         dfs(0, 0, ret, dir, 0, n, 0);

21         return ret;

22     }

23 };

 这段是iterative的方法,推荐

 1 class Solution {

 2 public:

 3     vector<vector<int> > generateMatrix(int n) {

 4         int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

 5         vector<vector<int> > ans(n, vector<int>(n));

 6         int x = 0;

 7         int y = 0;

 8         int cur = 1;

 9         for (int i = 0; i < n/2; ++i) {

10             for (int j = 0; j < 4; ++j) {

11                 for (int k = 0; k < n-1-2*i; ++k) {

12                     ans[x][y] = cur++;

13                     x += dir[j][0];

14                     y += dir[j][1];

15                 }

16             }

17             x += 1;

18             y += 1;

19         }

20         if (n % 2) ans[n/2][n/2] = cur;

21         return ans;

22     }

23 };

 C#

 1 public class Solution {

 2     public int[,] GenerateMatrix(int n) {

 3         int[,] dir = new int[4, 2] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

 4         int[,] ans = new int[n, n];

 5         int x = 0, y = 0, cur = 1;

 6         for (int i = 0; i < n/2; i++) {

 7             for (int j = 0; j < 4; j++) {

 8                 for (int k = 0; k < n-1-2*i; k++) {

 9                     ans[x, y] = cur++;

10                     x += dir[j, 0];

11                     y += dir[j, 1];

12                 }

13             }

14             x++;

15             y++;

16         }

17         if (n % 2 == 1) ans[n/2, n/2] = cur;

18         return ans;

19     }

20 }
View Code

 

你可能感兴趣的:(LeetCode)