classSolution{
public:int N, M;booldfs(vector<vector<char>>& board, string& word,int y,int x,int t){
if(t == word.size())returntrue;if(x <0|| x >= M || y <0|| y >= N || board[y][x]!= word[t])returnfalse;bool flag =false;int adds[4][2]={
{
-1,0},{
1,0},{
0,-1},{
0,1}};char temp = board[y][x];
board[y][x]='#';for(auto add : adds){
int yt = y + add[0], xt = x + add[1];
flag = flag ||dfs(board, word, yt, xt, t +1);}
board[y][x]= temp;return flag;}boolexist(vector<vector<char>>& board, string word){
if(!word.size())returntrue;
N = board.size(), M = board[0].size();for(int ii =0; ii < N; ii++){
for(int jj =0; jj < M; jj++){
bool flag =dfs(board, word, ii, jj,0);if(flag)returntrue;}}returnfalse;}};
classSolution{
public:int N, M;booldfs(vector<vector<char>>& board, vector<vector<bool>>& visited,string word,int y,int x,int t){
if(t == word.size())returntrue;if(x <0|| x >= M || y <0|| y >= N || visited[y][x]|| board[y][x]!= word[t])returnfalse;bool flag =false;intadd[4][2]={
{
-1,0},{
1,0},{
0,-1},{
0,1}};
visited[y][x]=true;for(auto temp :add){
int yt = y + temp[0], xt = x + temp[1];
flag = flag ||dfs(board, visited, word, yt, xt, t +1);}
visited[y][x]=false;return flag;}boolexist(vector<vector<char>>& board,string word){
if(!word.size())returntrue;
N = board.size(), M = board[0].size();
vector<vector<bool>>visited(N,vector(M,false));for(int ii =0; ii < N; ii++){
for(int jj =0; jj < M; jj++){
bool flag =dfs(board, visited, word, ii, jj,0);if(flag)returntrue;}}returnfalse;}};