|
| 1 | +/* |
| 2 | + 풀이: |
| 3 | + dfs를 이용해 board의 각 칸에서 출발해서 4방향으로 board를 탐색 |
| 4 | + word[index]와 일치하는 글자의 칸이 있으면 index + 1 시키면서 단어 끝 index까지 탐색 |
| 5 | +
|
| 6 | + - 탐색 중인 칸을 다른 char(#)로 바꿔서 이미 경로상에 있는 칸이라고 표시해주고 탐색 끝난 후 다시 되돌린다 |
| 7 | + - board를 변경할 수 없다면 unordered_set(해시테이블)로 중복 방문을 제거하거나 bool[row][col] 이중 배열로 방문된 칸 표시 |
| 8 | +
|
| 9 | + board 크기 : M * N, word 길이 W |
| 10 | +
|
| 11 | + TC : O(M * N * 4^W) |
| 12 | + board 전체 순회하고 각 칸 마다 4방향으로 word길이 만큼 재귀호출 |
| 13 | +
|
| 14 | + SC : O(W) |
| 15 | + 재귀호출 스택이 word의 길이와 비례 |
| 16 | +*/ |
| 17 | + |
| 18 | +class Solution { |
| 19 | + public: |
| 20 | + bool exist(vector<vector<char>>& board, string word) { |
| 21 | + for (int i = 0; i < board.size(); ++i) { |
| 22 | + for (int j = 0; j < board[0].size(); ++j) { |
| 23 | + if (dfs(board, word, i, j, 0)) { |
| 24 | + return true; |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + return false; |
| 29 | + } |
| 30 | + private: |
| 31 | + bool dfs(vector<vector<char>>& board, const string& word, int i, int j, int index) { |
| 32 | + if (index == word.size()) |
| 33 | + return true; |
| 34 | + if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size()) |
| 35 | + return false; |
| 36 | + if (board[i][j] != word[index]) |
| 37 | + return false; |
| 38 | + |
| 39 | + char tmp = board[i][j]; |
| 40 | + |
| 41 | + board[i][j] = '#'; |
| 42 | + bool found = dfs(board, word, i + 1, j, index + 1) || |
| 43 | + dfs(board, word, i - 1, j, index + 1) || |
| 44 | + dfs(board, word, i, j + 1, index + 1) || |
| 45 | + dfs(board, word, i, j - 1, index + 1); |
| 46 | + board[i][j] = tmp; |
| 47 | + |
| 48 | + return found; |
| 49 | + } |
| 50 | + }; |
0 commit comments