【Leetcode】79. Word Search
思路:
遍历矩阵,结合dfs解即可。
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 | #include <iostream> #include <vector> using namespace std; class Solution { public : Solution() {} bool exist(vector<vector< char >>& board, string word) { //初始化都没有被访问过 this ->rowCount = board.size(); if (rowCount == 0) { return false ; } this ->colCount = board[0].size(); for ( int i = 0; i < rowCount; i++) { vector< int > v(colCount, 0); visit.push_back(v); } this ->word = word; this ->board = board; for ( int i = 0; i < rowCount; i++){ for ( int j = 0; j< colCount; j++) { if (board[i][j] == word[0] && dfs(i, j, 0)) { return true ; } } } return false ; } /** *@param row 当前字符所在行 *@param col 当前字符所在列 *@param index word当前被扫描的位置 */ bool dfs( int row, int col, int index) { if (index == word.size() - 1) { return true ; } //当前位置标志为被访问 visit[row][col] = 1; //up if (row - 1 >= 0 && !visit[row - 1][col] && board[row - 1][col] == word[index + 1] ) { if (dfs(row - 1, col, index + 1)) { return true ; } } //down if (row + 1 < this ->rowCount && !visit[row + 1][col] && board[row + 1][col] == word[index + 1]) { if (dfs(row + 1, col, index + 1)) { return true ; } } //left if (col - 1 >= 0 && !visit[row][col - 1] && board[row][col - 1] == word[index + 1]) { if (dfs(row, col - 1, index + 1)) { return true ; } } //right if (col + 1 < this ->colCount && !visit[row][col + 1] && board[row][col + 1] == word[index + 1]) { if (dfs(row, col + 1, index + 1)) { return true ; } } //不满足,置为0 visit[row][col] = 0; return false ; } private : vector<vector< char >> board; string word; vector<vector< int >> visit; int rowCount; int colCount; }; int main( int argc, char *argv[]) { vector<vector< char >> board = { { 'a' , 'b' }}; Solution s; string word = "ba" ; bool ret = s.exist(board, word); cout<<ret<<endl; return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步