Word Search
DFS
์๊ณ ๋ฆฌ์ฆ : DFS DFS = ํ๊ณ ๋๋ ๋ฌธ์ ! ์กฐ๊ฑด์ ๋ง์กฑํ๋ฉด ๊ณ์ ๊น์ด ํ๊ณ ๋ ๋ค!
์๊ณ ๋ฆฌ์ฆ->Java๋ก ๊ตฌํ
class Solution {//DFS
int m,n;
int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
public boolean exist(char[][] board, String word) {
//error check
if(board == null ||board.length == 0 || board[0].length == 0) {return false;}
//creat and set value of data structure
m = board.length;
n = board[0].length;
boolean[][] visited = new boolean[m][n];
for(int i=0 ; i<m ; i++) {
for(int j=0; j<n ; j++) {
if(dfs(board,visited,i,j,0,word)) {return true;}//๊ณ์ ํ๊ณ ๋ ๋ค! ์ต์ข
์ ์ผ๋ก true์ด๋ฉด true๋ฅผ ๋ฆฌํด!
}
}
return false;
}
private boolean dfs(char[][] board, boolean[][] visited, int x, int y, int index, String word) {
if(index == word.length()) return true;//๋ง์ง๋ง ์ฒ ์๊น์ง ๋ค ๋น๊ตํ๋ฉด true๋ฅผ ๋ฆฌํดํ๊ฒ ๋๋ค.
if(x<0 || x>=m ||y<0 || y>=n) return false;
if(visited[x][y]) return false;//ํ๋ฒ ๋ฐฉ๋ฌธํ๋ ๊ฒ์ ๋ฐฉ๋ฌธํ์ง ์๊ธฐ ์ํด!
if(board[x][y] != word.charAt(index)) return false;
//board[x][y] == word.charAt(index) ์ ํ๋ฐ์ ์๋ค์ ์๋๋ฅผ ์ํ~!
visited[x][y] = true;
for(int[] dir:dirs) {//4๋ฐฉ์ผ๋ก ๋๋ฆฐ๋ค.
int newX = x + dir[0];
int newY = y + dir[1];
if(dfs(board,visited,newX,newY,index+1,word)){//๋ค์ ์ฒ ์์ ๋น๊ตํ๋ dfs ์ฌ๊ท ํธ์ถ!
return true;
}
}
visited[x][y] = false;//๋ค์ ์๊ฐ๊ธฐ ์ํด false๋ฅผ ์ ์ฅํ๊ณ , ์์ ํธ์ถํ ๊ณณ์ false๋ฆฌํดํ๋ค!
return false;
}
}
Last updated