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 =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word = "ABCB"
, -> returns false
.
class Solution {
public:
int dif[4][2] = {{0,1},{0,-1},{-1,0},{1,0}};
bool dfs(vector<vector<char>>& board, vector<vector<bool>> vis,string word,pair<int,int> idx,int k)
{
if(k==word.size())
return 1;
int n=board.size(),m=board[0].size(),x=idx.first,y=idx.second;
vis[x][y] = 1;
for(int i=0;i<4;++i)
{
int xx=x+dif[i][0],yy=y+dif[i][1];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&vis[xx][yy]==0&&board[xx][yy]==word[k])
if(dfs(board,vis,word,make_pair(xx,yy),k+1))
return 1;
}
return 0;
}
bool exist(vector<vector<char>>& board, string word) {
int n=board.size();
if(n==0) return 0;
int m=board[0].size();
vector<vector<bool>> vis(n,vector<bool>(m,0));
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
if(board[i][j]==word[0])
if(dfs(board,vis,word,make_pair(i,j),1))
return 1;
return 0;
}
};