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
.
算法思想:
深度优先搜索
struct node{
int x,y;
node(int a,int b):x(a),y(b){}
};
int fang[4][2]={-1,0,0,-1,1,0,0,1};
class Solution {
int r,c;
public:
bool dfs(int x,int y,int d,vector<vector<char> > &board,string &word,vector<vector<bool>> &visit){
if(d==word.size()-1)return true;
for(int i=0;i<4;i++){
int nx=x+fang[i][0];
int ny=y+fang[i][1];
if(nx>=0&&nx<r&&ny>=0&&ny<c&&!visit[nx][ny]&&board[nx][ny]==word[d+1]){
visit[nx][ny]=true;
if(dfs(nx,ny,d+1,board,word,visit))return true;
visit[nx][ny]=false;
}
}
return false;
}
bool exist(vector<vector<char> > &board, string word) {
if(board.empty())return false;
queue<node> que;
r=board.size();
c=board[0].size();
vector<vector<bool>> visit(r);
for(int i=0;i<r;i++)for(int j=0;j<c;j++)if(board[i][j]==word[0])que.push(node(i,j));
while(!que.empty()){
for(int i=0;i<r;i++)visit[i].assign(c,false);
node cur=que.front();
visit[cur.x][cur.y]=true;
if(dfs(cur.x,cur.y,0,board,word,visit))return true;
que.pop();
}
return false;
}
};