1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include <iostream> #include <vector> #include <string> #include <unordered_set> using namespace std;
class Solution { public: bool exist(vector<vector<char>>& board, string word) { m = board.size(), n = board[0].size();
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (dfs(board, word, i, j, 0)) { return true; } } }
return false; }
bool dfs(vector<vector<char>>& board, string& word, int x, int y, int start) { if (board[x][y] != word[start]) { return false; } if (start == word.size()-1) { return true; }
char c = board[x][y]; board[x][y] = '.'; for (int i = 0; i < 4; i++) { int a = x + dx[i], b = y + dy[i]; if (a >= 0 && a < m && b >= 0 && b < n && board[a][b] != '.') { if (dfs(board, word, a, b, start + 1)) { return true; } } } board[x][y] = c; return false; }
private: int m, n; int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 }; };
void printArray(const vector<vector<char>>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << "["; for (size_t j = 0; j < nums[i].size(); j++) { cout << "\"" <<nums[i][j] << "\""; if (j != nums[i].size() - 1) cout << ","; } cout << "]"; if (i != nums.size() - 1) cout << ","; } cout << "]"; }
int main() { Solution solution; vector<vector<vector<char>>> board_cases = { { {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'} }, { {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'} }, { {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'} } }; vector<string> word_cases = { "ABCCED", "SEE", "ABCB" };
for (size_t i = 0; i < board_cases.size(); i++) { auto& board = board_cases[i]; string word = word_cases[i];
cout << "Input: board = "; printArray(board); cout << ", word = " << word << endl;
bool result = solution.exist(board, word); cout << "Output: " << (result ? "true" : "false") << endl; }
return 0; }
|