⭐️⭐️
# 題目敘述
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n^2
in spiral order.
# Example 1
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
# Example 2
Input: n = 1
Output: [[1]]
# Solution
class Solution { | |
public: | |
vector<vector<int>> generateMatrix(int n) { | |
vector<vector<int>> res(n, vector<int>(n, 0)); | |
int left = 0, right = n-1, up = 0, down = n-1; | |
int val = 1; | |
while (left <= right && up <= down) { | |
for (int j=left; j<=right; j++) { | |
res[up][j] = val; | |
val++; | |
} | |
up++; | |
if (up > down) break; | |
for (int i=up; i<=down; i++) { | |
res[i][right] = val; | |
val++; | |
} | |
right--; | |
if (left > right) break; | |
for (int j=right; j>=left; j--) { | |
res[down][j] = val; | |
val++; | |
} | |
down--; | |
if (up > down) break; | |
for (int i=down; i>= up; i--) { | |
res[i][left] = val; | |
val++; | |
} | |
left++; | |
if (left > right) break; | |
} | |
return res; | |
} | |
}; |
class Solution { | |
public int[][] generateMatrix(int n) { | |
int[][] ans = new int[n][n]; | |
int count = 1; | |
int left = 0, right = n - 1, top = 0, bottom = n - 1; | |
while (left <= right && top <= bottom) { | |
for (int i = left; i <= right; i++) { | |
ans[top][i] = count++; | |
} | |
top++; | |
for (int i = top; i <= bottom; i++) { | |
ans[i][right] = count++; | |
} | |
right--; | |
if (top <= bottom) { | |
for (int i = right; i >= left; i--) { | |
ans[bottom][i] = count++; | |
} | |
bottom--; | |
} | |
if (left <= right) { | |
for (int i = bottom; i >= top; i--) { | |
ans[i][left] = count++; | |
} | |
left++; | |
} | |
} | |
return ans; | |
} | |
} |