@@ -66,14 +66,14 @@ class Solution:
66
66
ans = [[- 1 ] * n for _ in range (m)]
67
67
q = deque()
68
68
for i, row in enumerate (mat):
69
- for j, v in enumerate (row):
70
- if v == 0 :
69
+ for j, x in enumerate (row):
70
+ if x == 0 :
71
71
ans[i][j] = 0
72
72
q.append((i, j))
73
- dirs = [( 0 , 1 ), ( 0 , - 1 ), ( 1 , 0 ), ( - 1 , 0 )]
73
+ dirs = ( - 1 , 0 , 1 , 0 , - 1 )
74
74
while q:
75
75
i, j = q.popleft()
76
- for a, b in dirs:
76
+ for a, b in pairwise( dirs) :
77
77
x, y = i + a, j + b
78
78
if 0 <= x < m and 0 <= y < n and ans[x][y] == - 1 :
79
79
ans[x][y] = ans[i][j] + 1
@@ -87,30 +87,29 @@ class Solution:
87
87
88
88
``` java
89
89
class Solution {
90
-
91
90
public int [][] updateMatrix (int [][] mat ) {
92
91
int m = mat. length, n = mat[0 ]. length;
93
92
int [][] ans = new int [m][n];
94
- for (int i = 0 ; i < m; ++ i ) {
95
- Arrays . fill(ans[i] , - 1 );
93
+ for (int [] row : ans ) {
94
+ Arrays . fill(row , - 1 );
96
95
}
97
- Deque<int[]> q = new LinkedList <> ();
96
+ Deque<int[]> q = new ArrayDeque <> ();
98
97
for (int i = 0 ; i < m; ++ i) {
99
98
for (int j = 0 ; j < n; ++ j) {
100
99
if (mat[i][j] == 0 ) {
101
- ans[i][j] = 0 ;
102
100
q. offer(new int [] {i, j});
101
+ ans[i][j] = 0 ;
103
102
}
104
103
}
105
104
}
106
- int [] dirs = new int [] {- 1 , 0 , 1 , 0 , - 1 };
105
+ int [] dirs = {- 1 , 0 , 1 , 0 , - 1 };
107
106
while (! q. isEmpty()) {
108
- int [] t = q. poll();
109
- for ( int i = 0 ; i < 4 ; ++ i) {
110
- int x = t[ 0 ] + dirs[i];
111
- int y = t[ 1 ] + dirs[i + 1 ];
107
+ int [] p = q. poll();
108
+ int i = p[ 0 ], j = p[ 1 ];
109
+ for ( int k = 0 ; k < 4 ; ++ k) {
110
+ int x = i + dirs[k], y = j + dirs[k + 1 ];
112
111
if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == - 1 ) {
113
- ans[x][y] = ans[t[ 0 ]][t[ 1 ] ] + 1 ;
112
+ ans[x][y] = ans[i][j ] + 1 ;
114
113
q. offer(new int [] {x, y});
115
114
}
116
115
}
@@ -244,6 +243,36 @@ func updateMatrix(mat [][]int) [][]int {
244
243
}
245
244
```
246
245
246
+ ### ** TypeScript**
247
+
248
+ ``` ts
249
+ function updateMatrix(mat : number [][]): number [][] {
250
+ const [m, n] = [mat .length , mat [0 ].length ];
251
+ const ans: number [][] = Array .from ({ length: m }, () => Array .from ({ length: n }, () => - 1 ));
252
+ const q: [number , number ][] = [];
253
+ for (let i = 0 ; i < m ; ++ i ) {
254
+ for (let j = 0 ; j < n ; ++ j ) {
255
+ if (mat [i ][j ] === 0 ) {
256
+ q .push ([i , j ]);
257
+ ans [i ][j ] = 0 ;
258
+ }
259
+ }
260
+ }
261
+ const dirs: number [] = [- 1 , 0 , 1 , 0 , - 1 ];
262
+ while (q .length ) {
263
+ const [i, j] = q .shift ()! ;
264
+ for (let k = 0 ; k < 4 ; ++ k ) {
265
+ const [x, y] = [i + dirs [k ], j + dirs [k + 1 ]];
266
+ if (x >= 0 && x < m && y >= 0 && y < n && ans [x ][y ] === - 1 ) {
267
+ ans [x ][y ] = ans [i ][j ] + 1 ;
268
+ q .push ([x , y ]);
269
+ }
270
+ }
271
+ }
272
+ return ans ;
273
+ }
274
+ ```
275
+
247
276
### ** ...**
248
277
249
278
```
0 commit comments