首页 > 代码库 > Word Search
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。