|
| 1 | +/** |
| 2 | + * character들로 이루어진 m*n 행렬 board와 word 문자열이 주어질 때 해당 문자열이 행렬 내에 존재할 수 있는지 |
| 3 | + * 여부를 불린형으로 반환하세요. (상하좌우로 연결, 셀은 한번만 사용 가능) |
| 4 | + */ |
| 5 | +class Solution { |
| 6 | + |
| 7 | + int[] dx = {-1, 1, 0, 0}; |
| 8 | + |
| 9 | + int[] dy = {0, 0, -1, 1}; |
| 10 | + |
| 11 | + int rows, cols; |
| 12 | + |
| 13 | + // 시간 복잡도: O(M * N * 4^L) |
| 14 | + public boolean exist(char[][] board, String word) { |
| 15 | + rows = board.length; |
| 16 | + cols = board[0].length; |
| 17 | + |
| 18 | + // 셀 사용 여부를 나타내는 방문 배열 |
| 19 | + boolean[][] visited = new boolean[rows][cols]; |
| 20 | + |
| 21 | + for (int i = 0; i < rows; i++) { |
| 22 | + for (int j = 0; j < cols; j++) { |
| 23 | + // 글자의 시작점부터 DFS |
| 24 | + if (board[i][j] == word.charAt(0)) { |
| 25 | + if (dfs(i, j, 0, visited, board, word)) { |
| 26 | + return true; |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + return false; |
| 32 | + } |
| 33 | + |
| 34 | + // x, y가 board 벗어나지 않는지 |
| 35 | + private boolean isRange(int x, int y) { |
| 36 | + return x >= 0 && x < rows && y >= 0 && y < cols; |
| 37 | + } |
| 38 | + |
| 39 | + // DFS |
| 40 | + private boolean dfs(int x, int y, int idx, boolean[][] visited, char[][] board, String word) { |
| 41 | + |
| 42 | + if (idx == word.length()) { |
| 43 | + return true; |
| 44 | + } |
| 45 | + |
| 46 | + if (!isRange(x, y) || visited[x][y] || board[x][y] != word.charAt(idx)) { |
| 47 | + return false; |
| 48 | + } |
| 49 | + |
| 50 | + visited[x][y] = true; |
| 51 | + |
| 52 | + // 상하좌우 |
| 53 | + for (int i = 0; i < 4; i++) { |
| 54 | + int nx = x + dx[i]; |
| 55 | + int ny = y + dy[i]; |
| 56 | + if (dfs(nx, ny, idx + 1, visited, board, word)) { |
| 57 | + return true; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + visited[x][y] = false; |
| 62 | + |
| 63 | + return false; |
| 64 | + |
| 65 | + } |
| 66 | +} |
| 67 | + |
0 commit comments