|
| 1 | +/** |
| 2 | + * Runtime: 130ms |
| 3 | + * Time Complexity: O(m x n x 4^l) |
| 4 | + * - m: board의 행 길이 |
| 5 | + * - n: board의 열 길이 |
| 6 | + * - l: word의 길이 |
| 7 | + * |
| 8 | + * Memory: 42.32MB |
| 9 | + * Space Complexity: O(l) |
| 10 | + * |
| 11 | + * Approach: DFS + 백트래킹 |
| 12 | + * 1) board를 순회하며 word의 첫 글자와 일치하는 글자를 찾음 |
| 13 | + * 2) 일치하는 글자를 찾으면 DFS를 통해 상하좌우로 다음 글자를 찾음 |
| 14 | + * 3) 성능 최적화 |
| 15 | + * - 백트래킹을 위해 방문한 글자는 임시로 다른 문자('#')로 변경 (비트마스크) |
| 16 | + * - charAt 캐싱 |
| 17 | + */ |
| 18 | +class Solution { |
| 19 | + int[] dx = {-1, 1, 0, 0}; |
| 20 | + int[] dy = {0, 0, -1, 1}; |
| 21 | + |
| 22 | + public boolean exist(char[][] board, String word) { |
| 23 | + int m = board.length; |
| 24 | + int n = board[0].length; |
| 25 | + char startChar = word.charAt(0); |
| 26 | + |
| 27 | + for (int i=0; i<m; i++) { |
| 28 | + for (int j=0; j<n; j++) { |
| 29 | + if (board[i][j] == startChar) { |
| 30 | + if (dfs(board, i, j, 0, word)) { |
| 31 | + return true; |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return false; |
| 38 | + } |
| 39 | + |
| 40 | + private boolean dfs(char[][] board, int x, int y, int index, String word) { |
| 41 | + if (index == word.length()-1) { |
| 42 | + return true; |
| 43 | + } |
| 44 | + |
| 45 | + char temp = board[x][y]; |
| 46 | + char nextChar = word.charAt(index+1); |
| 47 | + board[x][y] = '#'; |
| 48 | + |
| 49 | + for (int i=0; i<4; i++) { |
| 50 | + int nx = x+dx[i]; |
| 51 | + int ny = y+dy[i]; |
| 52 | + |
| 53 | + if (nx >= 0 && nx < board.length && |
| 54 | + ny >= 0 && ny < board[0].length && |
| 55 | + board[nx][ny] == nextChar) { |
| 56 | + |
| 57 | + if (dfs(board, nx, ny, index+1, word)) { |
| 58 | + board[x][y] = temp; |
| 59 | + return true; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + board[x][y] = temp; |
| 65 | + return false; |
| 66 | + } |
| 67 | +} |
0 commit comments