File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+
4+ class Solution {
5+ static final int [] dx = {1 , - 1 , 0 , 0 };
6+ static final int [] dy = {0 , 0 , 1 , - 1 };
7+
8+ public int solution (int [][] maps ) {
9+ int n = maps. length;
10+ int m = maps[0 ]. length;
11+
12+ int [][] dist = new int [n][m];
13+ Queue<int[]> q = new ArrayDeque<> ();
14+
15+ dist[0 ][0 ] = 1 ;
16+ q. offer(new int []{0 , 0 });
17+
18+ while (! q. isEmpty()) {
19+ int [] cur = q. poll();
20+ int x = cur[0 ], y = cur[1 ];
21+
22+ if (x == n - 1 && y == m - 1 ) {
23+ return dist[x][y];
24+ }
25+
26+ for (int dir = 0 ; dir < 4 ; dir++ ) {
27+ int nx = x + dx[dir];
28+ int ny = y + dy[dir];
29+
30+ if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue ;
31+ if (maps[nx][ny] == 0 ) continue ;
32+ if (dist[nx][ny] != 0 ) continue ;
33+
34+ dist[nx][ny] = dist[x][y] + 1 ;
35+ q. offer(new int []{nx, ny});
36+ }
37+ }
38+
39+ return - 1 ;
40+ }
41+ }
42+
43+ ```
You can’t perform that action at this time.
0 commit comments