1+ import java .util .*;
2+ /*
3+ [1차 스스로 풀이] 163ms / 42.06 MB
4+ 1. 최단거리 문제는 bfs가 더 빠르겠지만, 여기서는 순서대로 밟고 가야 하는 경로가 있으므로 dfs
5+ 2. 보완할 점
6+ 1) exist함수에서 이중 for문으로 검사하는 것이 아닌 바로 dfs 호출하기 -> 기억에 안남
7+ 2) 재귀함수 호출하면서 return 하는 값을 잘 처리하고 싶음.
8+ */
9+ class Solution {
10+ static int [] dy = {-1 ,1 ,0 ,0 }, dx = {0 ,0 ,-1 ,1 };
11+ static int r ,c ;
12+
13+ public boolean exist (char [][] board , String word ) {
14+ r = board .length ; c = board [0 ].length ;
15+ boolean [][] visited = new boolean [r ][c ];
16+ int count = 0 ;
17+ boolean result = false ;
18+
19+ for (int i = 0 ; i < r ; i ++){
20+ for (int j = 0 ; j < c ; j ++){
21+ if (!visited [i ][j ] && word .charAt (count ) == board [i ][j ]){
22+ visited [i ][j ] = true ;
23+ result = dfs (count +1 , i , j , word , visited , board );
24+ System .out .println ("\n " );
25+ if (result ) return result ;
26+ visited [i ][j ] = false ;
27+ }
28+ }
29+ }
30+ return result ;
31+ }
32+ private boolean dfs (int count ,int y , int x , String word , boolean [][] visited , char [][] board ){
33+ if (count == word .length ()) return true ;
34+ boolean result = false ;
35+
36+ for (int d =0 ; d <4 ; d ++){
37+ int ny = y + dy [d ], nx = x + dx [d ];
38+
39+ if (inRange (ny ,nx ) && !visited [ny ][nx ] && word .charAt (count ) == board [ny ][nx ]){
40+ visited [ny ][nx ] = true ;
41+ result = dfs (count + 1 , ny , nx , word , visited ,board );
42+ if (result ) return result ;
43+ visited [ny ][nx ] = false ;
44+ }
45+ }
46+ return result ;
47+ }
48+
49+ private boolean inRange (int y , int x ){
50+ return -1 < y && y < r && -1 < x && x <c ;
51+ }
52+ }
53+
54+
55+ import java .util .*;
56+ /*
57+ [2차 최적화 코드 참고] 149ms / 41.62 MB
58+ 1. visited 배열 삭제, board 자체를 변경
59+ 2. 불필요 변수 count, result 제거
60+
61+ */
62+ class Solution {
63+ static int [] dy = {-1 ,1 ,0 ,0 }, dx = {0 ,0 ,-1 ,1 };
64+ static int r ,c ;
65+
66+ public boolean exist (char [][] board , String word ) {
67+ r = board .length ; c = board [0 ].length ;
68+
69+ for (int i = 0 ; i < r ; i ++){
70+ for (int j = 0 ; j < c ; j ++){
71+ if (word .charAt (0 ) == board [i ][j ]){
72+ if (dfs (1 , i , j , word , board )){
73+ return true ;
74+ }
75+ }
76+ }
77+ }
78+ return false ;
79+ }
80+ private boolean dfs (int count ,int y , int x , String word , char [][] board ){
81+ if (count == word .length ()) return true ;
82+
83+ char tmp = board [y ][x ];
84+ board [y ][x ] = '#' ;
85+
86+ for (int d =0 ; d <4 ; d ++){
87+ int ny = y + dy [d ], nx = x + dx [d ];
88+
89+ if (inRange (ny ,nx ) && board [ny ][nx ]!='#' && word .charAt (count ) == board [ny ][nx ]){
90+ if (dfs (count + 1 , ny , nx , word , board )){
91+ return true ;
92+ }
93+ }
94+ }
95+ board [y ][x ] = tmp ;
96+ return false ;
97+ }
98+
99+ private boolean inRange (int y , int x ){
100+ return -1 < y && y < r && -1 < x && x <c ;
101+ }
102+ }
0 commit comments