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
| #include <iostream> #include <vector> #include <string>
using namespace std;
vector<vector<int> > dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool checkpath(vector<vector<char> >& board, vector<vector<int> >&vis, int x, int y, string& word, int idx) { vis[x][y] = 1; if(idx == word.size()) return true; for(auto xy : dir){ int nextx = x + xy[0], nexty = y + xy[1]; if(nextx < 0 || nextx >= board.size() || nexty < 0 || nexty >= board[0].size() || vis[nextx][nexty] || board[nextx][nexty] != word[idx]) continue; else{ if(checkpath(board, vis, nextx, nexty, word, idx + 1)) return true; } } vis[x][y] = 0; return false; }
bool exist(vector<vector<char> >& board, string word) { int row = board.size(); if(row < 1) return false; int col = board[0].size(); if(col < 1) return false; vector<vector<int>>vis(row, vector<int>(col, 0)); for(int x = 0; x < row; x++){ for(int y = 0; y < col; y++){ if(board[x][y] == word[0]){ bool isexist = checkpath(board, vis, x, y, word, 1); if(isexist) return true; } } } return false; }
int main() { vector<vector<char> > board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}; string word = "ADECSE"; bool a = exist(board, word); cout << a << endl; return 0; }
|