|
| 1 | +/** |
| 2 | + * 풀이 |
| 3 | + * - dfs와 backtracking을 이용하여 풀었습니다 |
| 4 | + * |
| 5 | + * Big-O |
| 6 | + * - M: 주어진 grid `board`의 행 수 |
| 7 | + * - N: 주어진 grid `board`의 열 수 |
| 8 | + * - W: 주어진 string `word`의 size |
| 9 | + * |
| 10 | + * - Time complexity: O(M * N * 3 ^ W) |
| 11 | + * - `exist`함수가 grid 원소 모두를 조회합니다 -> O(M * N) |
| 12 | + * - 만약 `dfs`함수가 실행될 경우, 해당 함수는 최대 3방향에 대해 재귀호출을 실행합니다 (이전 좌표로는 `dfs`를 호출하지 않기 때문) |
| 13 | + * - 재귀 호출 스택의 크기는 주어진 string `word`의 길이에 비례합니다 -> O(3^W) |
| 14 | + * |
| 15 | + * - Space complexity: O(M * N + W) |
| 16 | + * - 재귀 호출 스택의 크기는 주어진 string `word`의 길이에 비례합니다 -> O(W) |
| 17 | + * - 탐색 여부를 기록하는 `visit` 배열의 크기는 `board`와 같습니다 -> O(M * N) |
| 18 | + */ |
| 19 | + |
| 20 | +class Solution { |
| 21 | +public: |
| 22 | + bool dfs(vector<vector<char>>& board, string word, vector<vector<bool>>& visit, int idx, int r, int c) { |
| 23 | + if (word.size() - 1 == idx) return true; |
| 24 | + |
| 25 | + pair<int, int> dirs[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; |
| 26 | + int R = board.size(); |
| 27 | + int C = board[0].size(); |
| 28 | + |
| 29 | + visit[r][c] = true; |
| 30 | + |
| 31 | + int next_idx = idx + 1; |
| 32 | + |
| 33 | + bool res = false; |
| 34 | + |
| 35 | + for (auto dir : dirs) { |
| 36 | + int next_r = r + dir.first; |
| 37 | + int next_c = c + dir.second; |
| 38 | + |
| 39 | + if (0 <= next_r && next_r < R && 0 <= next_c && next_c < C && !visit[next_r][next_c]) { |
| 40 | + if (board[next_r][next_c] == word[next_idx] && dfs(board, word, visit, next_idx, next_r, next_c)) { |
| 41 | + res = true; |
| 42 | + break; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + visit[r][c] = false; |
| 48 | + |
| 49 | + return res; |
| 50 | + } |
| 51 | + |
| 52 | + bool exist(vector<vector<char>>& board, string word) { |
| 53 | + int R = board.size(); |
| 54 | + int C = board[0].size(); |
| 55 | + vector<vector<bool>> visit; |
| 56 | + for (int i = 0; i < R; i++) { |
| 57 | + vector<bool> tmp; |
| 58 | + for (int j = 0; j < C; j++) { |
| 59 | + tmp.push_back(false); |
| 60 | + } |
| 61 | + visit.push_back(tmp); |
| 62 | + } |
| 63 | + |
| 64 | + for (int i = 0; i < R; i++) { |
| 65 | + for (int j = 0; j < C; j++) { |
| 66 | + if (board[i][j] == word[0] && dfs(board, word, visit, 0, i, j)) return true; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return false; |
| 71 | + } |
| 72 | +}; |
0 commit comments