@@ -28,4 +28,55 @@ boolean dfs(char[][] board,int i,int j,String word,int index){
28
28
return found ;
29
29
}
30
30
31
+ // 2์ฐจ์ ๋ฐฉ๋ฌธ ๋ฐฐ์ด์ ๋ง๋ค๊ณ direction ๋ฐฉํฅ ํ
ํ๋ฆฟ์ผ๋ก ํ์ด
32
+ public boolean exist2 (char [][] board , String word ) {
33
+ int m = board .length ;
34
+ int n = board [0 ].length ;
35
+ boolean [][] visited = new boolean [m ][n ];
36
+ boolean result = false ;
37
+
38
+ for (int i = 0 ; i < m ; i ++) {
39
+ for (int j = 0 ; j < n ; j ++) {
40
+ if (board [i ][j ] == word .charAt (0 )) {
41
+ result = backtrack (board , word , visited , i , j , 0 );
42
+ if (result )
43
+ return true ;
44
+ }
45
+ }
46
+ }
47
+
48
+ return false ;
49
+ }
50
+
51
+ private boolean backtrack (char [][] board , String word , boolean [][] visited , int i , int j , int index ) {
52
+ if (index == word .length ()) {
53
+ return true ;
54
+ }
55
+
56
+ // dfs๋ฅผ ํ ๋๋ ๋ฐฐ์ด ๋ฒ์๋ฅผ ๋ฒ์ด๋๋ ๊ฒฝ์ฐ break๋ฅผ ๊ผญ ๊ธฐ์ตํ๊ธฐ
57
+ if (i < 0 || i >= board .length || j < 0 || j >= board [0 ].length || visited [i ][j ]
58
+ || board [i ][j ] != word .charAt (index )) {
59
+ return false ;
60
+ }
61
+
62
+ visited [i ][j ] = true ;
63
+
64
+ // if๋ฌธ์์ ์์ฑํ๋ ๊ฒ์ด ๋์ ์ ์ต์ด์
65
+ // direction ํ
ํ๋ฆฟ์ ๋ง๋ค์ด์ for๋ฌธ์ผ๋ก ํด๊ฒฐํ๋ ์๊ธฐ๋ฒ์ผ๋ก ๋ณํ
66
+ int [][] directions = { { 1 , 0 }, { -1 , 0 }, { 0 , 1 }, { 0 , -1 } }; // ๊ทธ๋ฅ ์๊ธฐ
67
+
68
+ for (int [] dir : directions ) {
69
+ // i๊ฐ y, j๊ฐ x์ธ๋ฐ ์ฌ์ค 1, -1, 0๋ง ์ ์ค์ ํ๋ฉด ์๊ด์์. ๋ชฉ์ ์ 1, -1 1๋ฒ์ฉ ๊ทธ๋ฆฌ๊ณ ๋๋จธ์ง๋ 0์ผ๋ก ์ฑ์ฐ๋ ๊ฒ
70
+ int nextI = i + dir [0 ];
71
+ int nextJ = j + dir [1 ];
72
+
73
+ if (backtrack (board , word , visited , nextI , nextJ , index + 1 )) {
74
+ return true ;
75
+ }
76
+ }
77
+
78
+ visited [i ][j ] = false ;
79
+ return false ;
80
+ }
81
+
31
82
}
0 commit comments