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