File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ class Solution {
4+ static boolean [][] visit ;
5+ static int n ,m ;
6+ public int solution (int [][] maps ) {
7+ int answer = 0 ;
8+ n = maps .length ;
9+ m = maps [0 ].length ;
10+ visit = new boolean [maps .length ][maps [0 ].length ];
11+
12+ return bfs (maps );
13+ }
14+
15+ public int bfs (int [][] maps ) {
16+ Queue <int []> queue = new LinkedList <>();
17+ int [] dx = {1 ,-1 ,0 ,0 };
18+ int [] dy = {0 ,0 ,1 ,-1 };
19+ queue .offer (new int []{0 ,0 ,1 });
20+ visit [0 ][0 ] = true ;
21+ int count = 1 ;
22+ while (!queue .isEmpty ()) {
23+
24+ int [] a = queue .poll ();
25+ if (a [0 ] == n - 1 && a [1 ] == m - 1 ) {
26+ return a [2 ];
27+ }
28+ for (int i = 0 ; i < 4 ; i ++) {
29+ int cx = a [0 ] + dx [i ];
30+ int cy = a [1 ] + dy [i ];
31+ if (cx >= 0 && cy >= 0 && cx < n && cy < m && maps [cx ][cy ] == 1
32+ && !visit [cx ][cy ]) {
33+ visit [cx ][cy ] = true ;
34+ queue .offer (new int []{cx ,cy ,a [2 ] + 1 });
35+ count ++;
36+ }
37+ }
38+ }
39+ return -1 ;
40+ }
41+ }
You can’t perform that action at this time.
0 commit comments