Skip to content

Commit 13e2cef

Browse files
committed
feat: add typescript solution to lc problem: No.0059.Spiral Matrix II
1 parent f072972 commit 13e2cef

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

solution/0000-0099/0059.Spiral Matrix II/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,26 @@ class Solution {
104104
}
105105
```
106106

107+
### **TypeScript**
108+
109+
```ts
110+
function generateMatrix(n: number): number[][] {
111+
let ans = Array.from({ length: n }, v => new Array(n));
112+
let dir = [[0, 1], [1, 0], [0, -1], [-1, 0]];
113+
let i = 0, j = 0;
114+
for (let cnt = 1, k = 0; cnt <= n * n; cnt++) {
115+
ans[i][j] = cnt;
116+
let x = i + dir[k][0], y = j + dir[k][1];
117+
if (x < 0 || x == n || y < 0 || y == n || ans[x][y]) {
118+
k = (k + 1) % 4;
119+
x = i + dir[k][0], y = j + dir[k][1];
120+
}
121+
i = x, j = y;
122+
}
123+
return ans;
124+
};
125+
```
126+
107127
### **C++**
108128

109129
```cpp

solution/0000-0099/0059.Spiral Matrix II/README_EN.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,26 @@ class Solution {
9494
}
9595
```
9696

97+
### **TypeScript**
98+
99+
```ts
100+
function generateMatrix(n: number): number[][] {
101+
let ans = Array.from({ length: n }, v => new Array(n));
102+
let dir = [[0, 1], [1, 0], [0, -1], [-1, 0]];
103+
let i = 0, j = 0;
104+
for (let cnt = 1, k = 0; cnt <= n * n; cnt++) {
105+
ans[i][j] = cnt;
106+
let x = i + dir[k][0], y = j + dir[k][1];
107+
if (x < 0 || x == n || y < 0 || y == n || ans[x][y]) {
108+
k = (k + 1) % 4;
109+
x = i + dir[k][0], y = j + dir[k][1];
110+
}
111+
i = x, j = y;
112+
}
113+
return ans;
114+
};
115+
```
116+
97117
### **C++**
98118

99119
```cpp
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function generateMatrix(n: number): number[][] {
2+
let ans = Array.from({ length: n }, v => new Array(n));
3+
let dir = [[0, 1], [1, 0], [0, -1], [-1, 0]];
4+
let i = 0, j = 0;
5+
for (let cnt = 1, k = 0; cnt <= n * n; cnt++) {
6+
ans[i][j] = cnt;
7+
let x = i + dir[k][0], y = j + dir[k][1];
8+
if (x < 0 || x == n || y < 0 || y == n || ans[x][y]) {
9+
k = (k + 1) % 4;
10+
x = i + dir[k][0], y = j + dir[k][1];
11+
}
12+
i = x, j = y;
13+
}
14+
return ans;
15+
};

0 commit comments

Comments
 (0)