代码思路
第一反应就是普通的dfs。但是可能真的是因为半年没敲代码,很久没敲dfs了,疯狂debug。最后莫名其妙发现是因为LeetCode没有给出输入函数,自己憨批把输入函数写挂了。所以一个简单bug一直在莫名其妙的地方找。吐了吐了。ヽ(#`Д´)ノ
就是需要回溯的dfs,当搜索失败时需要恢复标记的点。可以在原数组标记,也可以直接建一个标记数组。
第一遍出Bug的代码(已修正bug)
class Solution {
public:
int dxy[4][2] = {
{
0,1},{
0,-1},{
1,0},{
-1,0}};
bool dfs(vector<vector<char> >& board,string &word,int Word_Index,int x,int y){
if(Word_Index == word.length()-1) return true;
board[x][y] = '.'; //先置换掉当前字母
for(int i = 0; i < 4; ++i){
int dx = x+dxy[i][0],dy = y+dxy[i][1];
if(dx >= 0 && dy >= 0 && dx < board.size() && dy < board[0].size() && board[dx][dy] == word[Word_Index+1] && dfs(board,word,Word_Index+1,dx,dy)) return true;
}
board[x][y] = word[Word_Index]; //前面未匹配成功,恢复
return false;
}
bool exist(vector<vector<char>>& board, string word) {
for(int i=0; i < board.size(); ++i){
for(int j = 0; j < board[i].size(); ++j){
if(board[i][j] == word[0] && dfs(board,word,0,i,j)) return true; //开始dfs
}
}
return false;
}
};
debug时全改的代码
class Solution {
public:
int dxy[4][2] = {
{
0,1},{
0,-1},{
1,0},{
-1,0}};
bool dfs(vector<vector<char> >& board,string &word,int Word_Index,int x,int y){
if(x < 0 || y < 0 || x >= board.size() || y>= board[0].size() || board[x][y] != word[Word_Index]) return false;
if(Word_Index == word.length()-1) return true;
board[x][y] = '.'; //先置换掉当前字母
if(dfs(board,word,Word_Index+1,x+1,y)||dfs(board,word,Word_Index+1,x-1,y)||dfs(board,word,Word_Index+1,x,y+1)||dfs(board,word,Word_Index+1,x,y-1)) return true;
board[x][y] = word[Word_Index]; //前面未匹配成功,恢复
return false;
}
bool exist(vector<vector<char>>& board, string word) {
for(int i=0; i < board.size(); ++i){
for(int j = 0; j < board[i].size(); ++j){
if(dfs(board,word,0,i,j)) return true; //开始dfs
}
}
return false;
}
};