描述:
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
例如,在下面的 3×4 的矩阵中包含单词 "ABCCED"(单词中的字母已标出)。
输入:
3 4 A B C E S F C S A D E E ABCCED
输出:
true
输入:
2 2 a b c d abcd
输出:
flase
题解:
从每一个方块开始搜索,递归该方块的上下左右四个方向,直至搜索到该单词结束
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool dfs(vector<vector<char>>& board, string word,int i,int j,int step){
int n = board.size();
int m = board[0].size();
if(step==word.size()){
return true;
}
if(step>word.size()||i<0||i>=n||j<0||j>=m||board[i][j]!=word[step]){
return false;
}
board[i][j]='\0';
bool res = (dfs(board,word,i-1,j,step+1)|| dfs(board,word,i,j-1,step+1)||
dfs(board,word,i+1,j,step+1)||dfs(board,word,i,j+1,step+1));
board[i][j]=word[step];
return res;
}
bool exist(vector<vector<char>>& board, string word) {
int n = board.size();
if(n<=0){
return false;
}
int m = board[0].size();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(board[i][j]==word[0]){
if(dfs(board,word,i,j,0)){
return true;
}
}
}
}
return false;
}
};
int main() {
vector<vector<char>> vec;
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++){
vector<char>tmp;
for(int j=0;j<m;j++){
char xx;
cin>>xx;
tmp.push_back(xx);
}
vec.push_back(tmp);
}
string str;
cin>>str;
Solution solution;
cout<<solution.exist(vec,str);
}