题目链接: https://leetcode.cn/problems/word-search/
题意:
给定二维char数组,询问是否能够有路径来获得给定的字符数组
无法改为动态规划表
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int n=board.size();
int m=board[0].size();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(f(board,n,m,word,i,j,0)){
return true;
}
}
}
return false;
}
bool f(vector<vector<char>>&board,int n,int m,string w,int i,int j,int k){
//basecase!
if(k==w.size()){
return true;
}
if(i<0||i>=n||j<0||j>=m||w[k]!=board[i][j])return false;
//try
bool ans=false;
char tmp=board[i][j];
board[i][j]='0';
ans=f(board,n,m,w,i-1,j,k+1)||f(board,n,m,w,i+1,j,k+1)||f(board,n,m,w,i,j-1,k+1)||f(board,n,m,w,i,j+1,k+1);
board[i][j]=tmp;
return ans;
}
};
标签:return,递归,int,单词,搜索,board,ans,false,size
From: https://www.cnblogs.com/benscode/p/18678361