leetcode : Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
深度搜索,用一个set<pair<int,int>>便是i,j节点是否已经走过了,每次访问一个节点便将该节点加入,如果找到则返回true,否则将改节点的visited信息从set中删除。
AC代码:
class Solution { public: bool exist(vector<vector<char> > &board, string word) { set<pair<int, int>> visited; for(int i = 0; i < board.size(); ++i){ for(int j = 0; j < board[0].size(); ++j){ if(dfs(i, j, board, word, visited)) return true; } } return false; } bool dfs(int i, int j, vector<vector<char>> &board, string word, set<pair<int, int>> &visited){ if(i < 0 || j < 0 || i == board.size() || j == board[0].size()) return false; else if(board[i][j] != word[0]) return false; else if(visited.find(make_pair(i, j)) != visited.end()) return false; else if(word.size() == 1) return true; else{ string sub = word.substr(1,word.size() - 1); visited.insert(make_pair(i, j)); bool ret = dfs(i + 1, j, board, sub, visited) || dfs(i - 1, j, board, sub, visited) || dfs(i, j - 1, board, sub, visited) || dfs(i, j + 1, board, sub, visited); visited.erase(visited.find(make_pair(i,j))); return ret; } } };
浙公网安备 33010602011771号