1
+ package WordSearch ;
2
+
3
+ /**
4
+ * User: Danyang
5
+ * Date: 1/26/2015
6
+ * Time: 14:16
7
+ *
8
+ * Given a 2D board and a word, find if the word exists in the grid.
9
+
10
+ The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally
11
+ or vertically neighboring. The same letter cell may not be used more than once.
12
+
13
+ For example,
14
+ Given board =
15
+
16
+ [
17
+ ["ABCE"],
18
+ ["SFCS"],
19
+ ["ADEE"]
20
+ ]
21
+ word = "ABCCED", -> returns true,
22
+ word = "SEE", -> returns true,
23
+ word = "ABCB", -> returns false.
24
+ */
25
+ public class Solution {
26
+ int [][] directions = new int [][] {{-1 , 0 }, {1 , 0 }, {0 , -1 }, {0 , 1 }};
27
+ /**
28
+ * O(N*2)*O(N*2)
29
+ * traverse + dfs
30
+ * @param board
31
+ * @param word
32
+ * @return
33
+ */
34
+ public boolean exist (char [][] board , String word ) {
35
+ int m = board .length ;
36
+ int n = board [0 ].length ;
37
+ boolean [][] visited = new boolean [m ][n ];
38
+ for (int i =0 ; i <m ; i ++)
39
+ for (int j =0 ; j <n ; j ++)
40
+ visited [i ][j ] = false ;
41
+
42
+
43
+ for (int i =0 ; i <m ; i ++)
44
+ for (int j =0 ; j <n ; j ++)
45
+ if (dfs (board , word , visited , 0 , i , j ))
46
+ return true ;
47
+ return false ;
48
+ }
49
+
50
+ boolean dfs (char [][] board , String word , boolean [][] visited , int cur , int i , int j ) {
51
+ int m = board .length ;
52
+ int n = board [0 ].length ;
53
+ if (board [i ][j ]==word .charAt (cur )) {
54
+ if (cur ==word .length ()-1 )
55
+ return true ;
56
+ visited [i ][j ] = true ;
57
+ for (int dir =0 ; dir <4 ; dir ++) {
58
+ int next_i = i +directions [dir ][0 ];
59
+ int next_j = j +directions [dir ][1 ];
60
+ if (next_i >=0 && next_i <m && next_j >=0 && next_j <n && !visited [next_i ][next_j ]) {
61
+ if (dfs (board , word , visited , cur +1 , next_i , next_j ))
62
+ return true ;
63
+ }
64
+ }
65
+ visited [i ][j ] = false ;
66
+ }
67
+ return false ;
68
+ }
69
+
70
+ public static void main (String [] args ) {
71
+ new Solution ().exist (new char [][] {{'a' , 'a' }}, "aa" );
72
+ }
73
+ }
0 commit comments