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​​.



class Solution {
public:
//DFS搜索 递归调用搜索
bool exist(vector<vector<char> > &board, string word) {

int m,n,i,j;
m=board.size();
n=board[0].size();
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(board[i][j]==word[0])
{
vector< vector<char> > tmp(board);
bool res=dfs(tmp,i,j,word,0);
if(res==true)
return true;
}
}
}
return false;
}

bool dfs(vector<vector<char> > &board, int i,int j,string word,int index)
{
if(index==word.size())
return true;
if(i>=0&&i<board.size()&&j>=0&&j<board[0].size()&&board[i][j]==word[index])
{
char s=board[i][j];
board[i][j]='@';
index++;
bool f=(dfs(board,i+1,j,word,index)||dfs(board,i,j+1,word,index)||dfs(board,i-1,j,word,index)||dfs(board,i,j-1,word,index));
//注意回溯
if(f)
return true;
else
board[i][j] = s;
}
return false;
}
};