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: int n,n1,n2; bool exist(vector<vector<char> > &board, string word) { n1=board.size();
n2=board[].size();
n=word.length(); bool flag=false; //vector<vector<bool> > visited(n1,vector<bool>(n2,false)); bool **visited=new bool*[n1];
for(int i=;i<n1;i++)
{
visited[i]=new bool[n2];
for(int j=;j<n2;j++)
{
visited[i][j]=false;
}
} for(int i=;i<n1;i++)
{
for(int j=;j<n2;j++)
{
if(board[i][j]==word[])
{
//注意visited采用引用传值
flag=flag||dfs(board,word,i,j,visited);
if(flag) return true;
}
}
} for(int i=;i<n1;i++) delete[] visited[i]; return false;
} bool dfs(vector<vector<char> > &board,string &word,int i,int j,bool** &visited,int index=)
{ if(board[i][j]!=word[index]||visited[i][j]) return false;
if(index==n-) return true; visited[i][j]=true; bool flag1=i+<n1&&dfs(board,word,i+,j,visited,index+);
bool flag2=j+<n2&&dfs(board,word,i,j+,visited,index+);
bool flag3=j->=&&dfs(board,word,i,j-,visited,index+);
bool flag4=i->=&&dfs(board,word,i-,j,visited,index+); bool result=flag1||flag2||flag3||flag4; //由于是引用传值,所以没有找到的目标串时要把visited复原
//if(result==false) visited[i][j]=false;
visited[i][j]=result;
return result;
}
};