|
| 1 | +class Solution { |
| 2 | + public boolean exist(char[][] board, String word) { |
| 3 | + int m = board.length; |
| 4 | + int n = board[0].length; |
| 5 | + for(int i = 0; i < m; i++) { |
| 6 | + for(int j = 0; j < n; j++) { |
| 7 | + if(dfs(board, i, j, word, 0)) { |
| 8 | + return true; |
| 9 | + } |
| 10 | + } |
| 11 | + } |
| 12 | + return false; |
| 13 | + } |
| 14 | + |
| 15 | + boolean dfs(char[][] board,int i,int j,String word,int index){ |
| 16 | + if(index == word.length()) return true; |
| 17 | + if(i<0 || j<0 || i>=board.length || j>=board[0].length) return false; // ๋ฒ์๋ฅผ ๋ฒ์ด๋ ๊ฒฝ์ฐ |
| 18 | + if(board[i][j] != word.charAt(index)) return false; // ์ผ์น ์กฐ๊ฑด์ ๋ถ๋ง์กฑํ๋ ๊ฒฝ์ฐ |
| 19 | + |
| 20 | + char temp = board[i][j]; |
| 21 | + board[i][j] = '#'; |
| 22 | + boolean found = dfs(board, i+1, j, word, index+1) |
| 23 | + || dfs(board, i-1, j, word, index+1) |
| 24 | + || dfs(board, i, j+1, word, index+1) |
| 25 | + || dfs(board, i, j-1, word, index+1); |
| 26 | + |
| 27 | + board[i][j] = temp; |
| 28 | + return found; |
| 29 | + } |
| 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 | + |
| 82 | +} |
0 commit comments