classSolution { private: constint directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> ans(n, vector<int>(n)); int d = 0, x = 0, y = 0; for (int i = 1; i <= n * n; i++) { ans[x][y] = i; int nx = x + directions[d][0]; int ny = y + directions[d][1]; if (nx < 0 || nx == n || ny < 0 || ny == n || ans[nx][ny]) { d = (d + 1) % 4; nx = x + directions[d][0]; ny = y + directions[d][1]; } x = nx, y = ny; } return ans; } };
defgenerateMatrix(self, n: int) -> List[List[int]]: ans = [[0] * n for _ inrange(n)] d = x = y = 0 for i inrange(n * n): ans[x][y] = i + 1 nx, ny = x + self.directions[d][0], y + self.directions[d][1] if nx == n or nx < 0or ny == n or ny < 0or ans[nx][ny]: d = (d + 1) % 4 nx, ny = x + self.directions[d][0], y + self.directions[d][1] x, y = nx, ny return ans
publicint[][] generateMatrix(int n) { int[][] ans = newint[n][n]; intd=0, x = 0, y = 0; for (inti=1; i <= n * n; i++) { ans[x][y] = i; intnx= x + directions[d][0]; intny= y + directions[d][1]; if (nx == n || nx < 0 || ny == n || ny < 0 || ans[nx][ny] > 0) { d = (d + 1) % 4; nx = x + directions[d][0]; ny = y + directions[d][1]; } x = nx; y = ny; } return ans; } }
funcgenerateMatrix(n int) [][]int { ans := make([][]int, n) for i := range ans { ans[i] = make([]int, n) } d, x, y := 0, 0, 0 for i := 1; i <= n * n; i++ { ans[x][y] = i nx, ny := x + directions[d][0], y + directions[d][1] if nx == n || nx < 0 || ny == n || ny < 0 || ans[nx][ny] > 0 { d = (d + 1) % 4 nx, ny = x + directions[d][0], y + directions[d][1] } x, y = nx, ny } return ans }