|
| 1 | +class Solution { |
| 2 | + private static final int[][] DIRECTIONS = { |
| 3 | + {-1, 0}, |
| 4 | + {1, 0}, |
| 5 | + {0, -1}, |
| 6 | + {0, 1} |
| 7 | + }; |
| 8 | + |
| 9 | + private char[][] board; |
| 10 | + private String word; |
| 11 | + private boolean[][] visited; |
| 12 | + private int rows; |
| 13 | + private int cols; |
| 14 | + |
| 15 | + public boolean exist(char[][] board, String word) { |
| 16 | + this.board = board; |
| 17 | + this.word = word; |
| 18 | + this.rows = board.length; |
| 19 | + this.cols = board[0].length; |
| 20 | + this.visited = new boolean[rows][cols]; |
| 21 | + |
| 22 | + // 단어가 전체 칸보다 길면 경로를 만들 수 없다. |
| 23 | + if (word.length() > rows * cols) { |
| 24 | + return false; |
| 25 | + } |
| 26 | + |
| 27 | + for (int row = 0; row < rows; row++) { |
| 28 | + for (int col = 0; col < cols; col++) { |
| 29 | + // 첫 문자가 일치하는 위치에서만 탐색을 시작한다. |
| 30 | + if (board[row][col] == word.charAt(0) |
| 31 | + && search(row, col, 0)) { |
| 32 | + return true; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return false; |
| 38 | + } |
| 39 | + |
| 40 | + private boolean search(int row, int col, int wordIndex) { |
| 41 | + // 이미 현재 경로에서 사용한 칸이거나 문자가 다르면 탐색을 중단한다. |
| 42 | + if (visited[row][col] |
| 43 | + || board[row][col] != word.charAt(wordIndex)) { |
| 44 | + return false; |
| 45 | + } |
| 46 | + |
| 47 | + // 마지막 문자까지 일치했다면 단어를 찾은 것이다. |
| 48 | + if (wordIndex == word.length() - 1) { |
| 49 | + return true; |
| 50 | + } |
| 51 | + |
| 52 | + visited[row][col] = true; |
| 53 | + |
| 54 | + for (int[] direction : DIRECTIONS) { |
| 55 | + int nextRow = row + direction[0]; |
| 56 | + int nextCol = col + direction[1]; |
| 57 | + |
| 58 | + if (!isInBounds(nextRow, nextCol)) { |
| 59 | + continue; |
| 60 | + } |
| 61 | + |
| 62 | + if (search(nextRow, nextCol, wordIndex + 1)) { |
| 63 | + visited[row][col] = false; |
| 64 | + return true; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + // 다른 경로에서 현재 칸을 다시 사용할 수 있도록 방문 상태를 복구한다. |
| 69 | + visited[row][col] = false; |
| 70 | + return false; |
| 71 | + } |
| 72 | + |
| 73 | + private boolean isInBounds(int row, int col) { |
| 74 | + return row >= 0 && row < rows |
| 75 | + && col >= 0 && col < cols; |
| 76 | + } |
| 77 | +} |
0 commit comments