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
| class Solution { public: bool exist(vector<vector<char>>& board, string word) {
for (i = 0; i < board.size(); i++) { for (j = 0; j < board[0].size(); j++) {
if (DFC(i, j, board, word)) { return true;} } } return false; }
private: bool DFC(int i, int j, vector<vector<char>>& board, string words) { if (words.length() == 0) { return true;} if (i >= board.size() || i < 0 || j >= board[0].size() || j < 0 || board[i][j] != word[0]) {return false;}
char temp = board[i][j]; board[i][j] = ' '; string tempW = words.substr(1); bool res = DFC(i+1, j, board, tempW) || DFC(i-1, j, board, tempW) || DFC(i, j+1, board, tempW) || DFC(i, j-1, board, tempW); board[i][j] = temp;
return res; } private: int i; int j; };
|