code ideas
The first reaction is ordinary dfs. But it may really be because I haven't typed code for half a year, haven't typed dfs for a long time, and debugged like crazy. Finally, inexplicably found that because LeetCode did not provide the input function, I foolishly wrote the input function and hung up. So a simple bug has been looking for inexplicable places. vomited. ヽ(#`Д´)ノ
is the dfs that needs to be backtracked. When the search fails, the marked point needs to be restored. You can mark the original array, or you can directly create a marked array.
The first time out of the bug code (bugs have been fixed)
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;
}
};
Fully modified code when debugging
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;
}
};