1
+ // NOTE: Queue를 처음에 써서 탐색하며 꼬여버리는 문제가 있었다..
2
+ // NOTE: 원본 문자의 index를 사용해서 해결.
3
+
4
+ import java .util .LinkedList ;
5
+ import java .util .Queue ;
6
+
7
+ class Solution {
8
+
9
+ public boolean [][] visit ;
10
+ int w = 0 ;
11
+ int h = 0 ;
12
+ int [] dx = {1 , 0 , -1 , 0 };
13
+ int [] dy = {0 , 1 , 0 , -1 };
14
+
15
+ public boolean exist (char [][] board , String word ) {
16
+
17
+ char [] cArr = word .toCharArray ();
18
+ w = board .length ;
19
+ h = board [0 ].length ;
20
+ visit = new boolean [w ][h ];
21
+
22
+ for (int i = 0 ; i < board .length ; i ++) {
23
+ for (int j = 0 ; j < board [0 ].length ; j ++) {
24
+ if (cArr [0 ] == board [i ][j ]) {
25
+
26
+ if (dfs (board , word , i , j , 0 )) {
27
+ return true ;
28
+ }
29
+ }
30
+ }
31
+ }
32
+
33
+ return false ;
34
+ }
35
+
36
+ public boolean dfs (char [][] b , String word , int x , int y , int idx ) {
37
+ if (idx == word .length ()) return true ;
38
+
39
+ if (x < 0 || x >= w || y < 0 || y >= h || b [x ][y ] != word .charAt (idx ) || visit [x ][y ]) {
40
+ return false ;
41
+ }
42
+
43
+ visit [x ][y ] = true ;
44
+
45
+ for (int i = 0 ; i < 4 ; i ++) {
46
+ int nx = x + dx [i ];
47
+ int ny = y + dy [i ];
48
+
49
+ if (dfs (b , word , nx , ny , idx + 1 )) {
50
+ return true ;
51
+ }
52
+ }
53
+
54
+ visit [x ][y ] = false ;
55
+ return false ;
56
+ }
57
+
58
+
59
+
60
+ class WrongSolution {
61
+
62
+ public boolean [][] visit ;
63
+ Queue <Character > q = new LinkedList ();
64
+ int w = 0 ;
65
+ int h = 0 ;
66
+ int [] dx = {1 , 0 , -1 , 0 };
67
+ int [] dy = {0 , 1 , 0 , -1 };
68
+
69
+ public boolean exist (char [][] board , String word ) {
70
+
71
+ char [] cArr = word .toCharArray ();
72
+ w = board .length ;
73
+ h = board [0 ].length ;
74
+ visit = new boolean [w ][h ];
75
+
76
+ for (int i = 0 ; i < board .length ; i ++) {
77
+ for (int j = 0 ; j < board [0 ].length ; j ++) {
78
+ if (cArr [0 ] == board [i ][j ]) {
79
+ q = new LinkedList ();
80
+ visit = new boolean [w ][h ];
81
+ for (char c : word .toCharArray ()) {
82
+ q .add (c );
83
+ }
84
+
85
+
86
+ dfs (board , i , j );
87
+ if (q .isEmpty ()) {
88
+ return true ;
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ return false ;
95
+ }
96
+
97
+ public void dfs (char [][] b , int x , int y ) {
98
+ if (x < 0 || x >= w || y < 0 || y >= h || visit [x ][y ]) {
99
+ return ;
100
+ }
101
+
102
+ if (q .isEmpty ()) {
103
+ return ;
104
+ }
105
+
106
+ if (b [x ][y ] != q .peek ()) {
107
+ return ;
108
+ }
109
+
110
+ q .poll ();
111
+ visit [x ][y ] = true ;
112
+
113
+ for (int i = 0 ; i < 4 ; i ++) {
114
+ int nx = x + dx [i ];
115
+ int ny = y + dy [i ];
116
+
117
+ dfs (b , nx , ny );
118
+ }
119
+ }
120
+ }}
0 commit comments