|
| 1 | +// time complexity: O(n * m * 3 ^ L), L은 최대 깊이 |
| 2 | +// spatial complexity: O((n * m ) ^ 2) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + bool exist(vector<vector<char>>& board, string word) { |
| 7 | + vector<vector<bool>> visit; |
| 8 | + for(int i = 0; i < board.size(); ++i) { |
| 9 | + for(int j = 0; j < board[0].size(); ++j) { |
| 10 | + if(board[i][j] != word[0]) continue; |
| 11 | + visit = vector(board.size(), vector(board[0].size(), false)); |
| 12 | + visit[i][j] = true; |
| 13 | + if (find(board, word, 1, {i,j}, visit)) { |
| 14 | + return true; |
| 15 | + } |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + return false; |
| 20 | + } |
| 21 | + |
| 22 | + bool find( |
| 23 | + vector<vector<char>>& board, |
| 24 | + string word, |
| 25 | + int fi, |
| 26 | + pair<int,int> curPos, |
| 27 | + vector<vector<bool>>& visit |
| 28 | + ) { |
| 29 | + if(fi == word.length()) { |
| 30 | + return true; |
| 31 | + } |
| 32 | + |
| 33 | + char target = word[fi]; |
| 34 | + int nr,ny; |
| 35 | + for(int i = 0; i < 4; ++i) { |
| 36 | + nr = curPos.first + DIRECTIONS[i][0]; |
| 37 | + ny = curPos.second+ DIRECTIONS[i][1]; |
| 38 | + |
| 39 | + if (isOutSideOfBoard({nr,ny}, {board.size(), board[0].size()}) || visit[nr][ny] || board[nr][ny] != target) { |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + visit[nr][ny] = true; |
| 44 | + if(find(board, word, fi + 1, {nr,ny}, visit)) { |
| 45 | + return true; |
| 46 | + } |
| 47 | + visit[nr][ny] = false; |
| 48 | + } |
| 49 | + |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + int DIRECTIONS[4][2] = { |
| 54 | + {-1, 0}, |
| 55 | + {0, 1}, |
| 56 | + {1, 0}, |
| 57 | + {0, -1}, |
| 58 | + }; |
| 59 | + |
| 60 | + bool isOutSideOfBoard(pair<int,int> cur, pair<int,int> boardSize) { |
| 61 | + return cur.first < 0 || cur.second < 0 || cur.first >= boardSize.first || cur.second >= boardSize.second; |
| 62 | + } |
| 63 | +}; |
0 commit comments