LeetCode 劍指 Offer 12. 矩陣中的路徑(dfs)
阿新 • • 發佈:2021-02-19
題意:
請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。
路徑可以從矩陣中的任意一格開始,每一步可以在矩陣中向左、右、上、下移動一格。
如果一條路徑經過了矩陣的某一格,那麼該路徑不能再次進入該格子。
例如,在下面的3×4的矩陣中包含一條字串“bfce”的路徑(路徑中的字母用加粗標出)。
[["a","b","c","e"],
["s","f","c","s"],
["a","d" ,"e","e"]]
但矩陣中不包含字串“abfb”的路徑,
因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入這個格子。
資料範圍:
1 <= board.length <= 200
1 <= board[i].length <= 200
1<=word.length<=1e3
解法:
dfs所有方案,不剪枝的話複雜度也只有O(n*m*len)=4e7.
code:
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int mark[222][222];
class Solution {
public:
int n,m,p;
int dfs(vector<vector<char>>& a, string& s,int i,int j,int cur){
if(a[i][j]!=s[cur])return 0;
if(cur==p-1)return 1;
for(int k=0;k<4;k++){
int xx=i+dx[k];
int yy=j+dy[k];
if(xx<0||xx>=n|| yy<0||yy>=m)continue;
if(mark[xx][yy])continue;
mark[xx][yy]=1;
int t=dfs(a,s,xx,yy,cur+1);
mark[xx][yy]=0;
if(t)return 1;
}
return 0;
}
bool exist(vector<vector<char>>& a, string s) {
n=a.size(),m=a[0].size(),p=s.size();
memset(mark,0,sizeof mark);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
mark[i][j]=1;
if(dfs(a,s,i,j,0)){
return 1;
}
mark[i][j]=0;
}
}
return 0;
}
};