Thursday, June 23, 2016

59. Spiral Matrix II

Only need some math.

1:  class Solution {  
2:  public:  
3:    vector<vector<int>> generateMatrix(int n) {  
4:      int i = 0, k = 1;  
5:      vector<vector<int>> res(n, vector<int>(n, 0));  
6:      while (k <= n*n) {  
7:        int j = i;  
8:        while (j < n - i) {  
9:          res[i][j++] = k++;  
10:        }  
11:        j = i+1;  
12:        while (j < n - i) {  
13:          res[j++][n-i-1] = k++;  
14:        }  
15:        j = n - i - 2;  
16:        while (j > i) {  
17:          res[n-i-1][j--] = k++;  
18:        }  
19:        j = n - i - 1;  
20:        while (j > i) {  
21:          res[j--][i] = k++;  
22:        }  
23:        i++;  
24:      }  
25:      return res;  
26:    }  
27:  };  

There is a better way to solve this problem, same as problem "54. Spiral Matrix"

1:  class Solution {  
2:  public:  
3:    vector<vector<int>> generateMatrix(int n) {  
4:      vector<vector<int>> res(n, vector<int>(n, 0));  
5:      int rowBegin = 0, colBegin = 0;  
6:      int rowEnd = n-1, colEnd = n-1;  
7:      int k = 1;  
8:      while (rowBegin <= rowEnd) {  
9:        for (int j = colBegin; j <= colEnd; j++) res[rowBegin][j] = k++;  
10:        rowBegin++;  
11:        for (int i = rowBegin; i <= rowEnd; i++) res[i][colEnd] = k++;  
12:        colEnd--;  
13:        if (rowBegin <= rowEnd) {  
14:          for (int j = colEnd; j >= colBegin; j--) res[rowEnd][j] = k++;  
15:        }  
16:        rowEnd--;  
17:        if (colBegin <= colEnd) {  
18:          for (int i = rowEnd; i >= rowBegin; i--) res[i][colBegin] = k++;  
19:        }  
20:        colBegin++;  
21:      }  
22:      return res;  
23:    }  
24:  };  

No comments:

Post a Comment