This file contains 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
class Solution { | |
public: | |
vector<vector<int>> generateMatrix(int n) { | |
vector<vector<int>> matrix(n, vector<int>(n)); | |
vector<pair<int, int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; | |
int curr = 1, layers = (n + 1) / 2; | |
for(int k = 0; k < layers; ++k) | |
{ | |
int i = k, j = k, count = 0; | |
while(count < 4 * (n - 2 * k - 1)) | |
{ | |
matrix[i][j] = curr++; | |
auto dir = dirs[count / (n - 2 * k - 1)]; | |
i += dir.first; | |
j += dir.second; | |
++count; | |
} | |
//If layer numbers is odd, we have to handle last layer specially | |
if(!count) | |
matrix[k][k] = curr++; | |
} | |
return matrix; | |
} | |
}; |
No comments:
Post a Comment