Word Search
Posted xpp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Word Search相关的知识,希望对你有一定的参考价值。
方法:使用递归的方式实现:
class Solution { public: bool exist(vector<vector<char>>& board, string word) { int m = board.size(), n = board[0].size(); vector<vector<bool>> visited = vector<vector<bool>>(m, vector<bool>(n, false)); for(int i=0; i<m; ++i) { for(int j=0; j<n; ++j) { if(dfs(board, visited, word, i, j, 0)) return true; } } return false; } bool dfs(vector<vector<char>> &board, vector<vector<bool>> &visited, string &word, int i, int j, int index) { if(index == word.size()) return true; if(i < 0 || j < 0 || i >= board.size() || j >= board[0].size()) return false; if(word[index] != board[i][j]) return false; if(visited[i][j]) return false; visited[i][j] = true; bool ret = dfs(board, visited, word, i-1, j, index+1) || dfs(board, visited, word, i+1, j, index+1) || dfs(board, visited, word, i, j-1, index+1) || dfs(board, visited, word, i, j+1, index+1); visited[i][j] = false; return ret; } };
以上是关于Word Search的主要内容,如果未能解决你的问题,请参考以下文章
79. Word Search/212. Word Search II--图的back tracking -- tier tree 待续