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+ /**
2+ * @param {number[] } start
3+ * @param {number[] } target
4+ * @return {boolean }
5+ */
6+ var canReach = function ( start , target ) {
7+ const dirs = [
8+ [ - 1 , - 2 ] ,
9+ [ - 2 , - 1 ] ,
10+ [ - 2 , 1 ] ,
11+ [ - 1 , 2 ] ,
12+ [ 1 , 2 ] ,
13+ [ 2 , 1 ] ,
14+ [ 2 , - 1 ] ,
15+ [ 1 , - 2 ] ,
16+ ] ;
17+ const visited = Array ( 8 ) ;
18+ for ( let i = 0 ; i < 8 ; i ++ ) {
19+ visited [ i ] = Array . from ( { length : 8 } , ( ) => Array ( 2 ) ) ;
20+ }
21+ const startX = start [ 0 ] ;
22+ const startY = start [ 1 ] ;
23+ const queue = [ [ startX , startY , true ] ] ;
24+ let head = 0 ;
25+ visited [ startX ] [ startY ] [ 1 ] = true ;
26+
27+ while ( queue . length - head > 0 ) {
28+ const [ curX , curY , curFlag ] = queue [ head ++ ] ;
29+ if ( curX === target [ 0 ] && curY === target [ 1 ] && curFlag ) return true ;
30+ for ( const [ dirX , dirY ] of dirs ) {
31+ const nextX = dirX + curX ;
32+ const nextY = dirY + curY ;
33+ const nextFlag = ! curFlag ;
34+
35+ if ( nextX < 0 || nextY < 0 || nextX >= 8 || nextY >= 8 ) continue ;
36+ if ( visited [ nextX ] [ nextY ] [ nextFlag === true ? 1 : 0 ] ) {
37+ continue ;
38+ }
39+ visited [ nextX ] [ nextY ] [ nextFlag === true ? 1 : 0 ] = true ;
40+ queue . push ( [ nextX , nextY , nextFlag ] ) ;
41+ }
42+ }
43+ return false ;
44+ } ;
You can’t perform that action at this time.
0 commit comments