题目:题目链接
思路:题意就是从m*n的矩阵中找到一串连续的字符串与目标字符串相同。直接dfs。
看代码:
class Solution {
public:
int dis[4][2] = { {0,1},{1,0},{-1,0},{0,-1} };//上下左右四个方向
bool vis[10][10];//标记数组,记录该位置是否访问过
int n, m;//分别表示长和宽
bool f = 0;//用于记录是否找到答案
bool isInBorder(int x, int y) {//判断是否越界
if (x >= 0 && x < m && y >= 0 && y < n) return true;
return false;
}
void dfs(vector<vector<char>>& board, int x, int y, int now_len, string now_word, string word) {
//x,y表示当前坐标,now_word表示当前字符串,word为目标字符串
if (now_word == word) {
//边界条件
f = 1;
return;
}
if (f || now_len > word.size()) return;//找到了或者长度不符。
for (int i = 0; i < 4; ++i) {//对于四个方向都进行搜索
int now_x = x + dis[i][0];
int now_y = y + dis[i][1];
if (isInBorder(now_x, now_y) && !vis[now_x][now_y]) {//没出界而且没有搜索过
if (board[now_x][now_y] == word[now_len]) {//当前字符与对应字符相同
vis[now_x][now_y] = 1;//已访问
dfs(board, now_x, now_y, now_len + 1, now_word + board[now_x][now_y], word);
vis[now_x][now_y] = 0;//标记回退
}
}
}
return;
}
bool exist(vector<vector<char>>& board, string word) {
m = board.size();
n = board[0].size();
if (m * n < word.size()) return false;//长度不满足
string str = "";//记录当前字符串
for (int i = 0; i < m; ++i) {//以所有坐标的元素为起点
for (int j = 0; j < n; ++j) {
if (board[i][j] == word[0]) {
str = word[0];
vis[i][j] = 1;
dfs(board, i, j, 1, str, word);
vis[i][j] = 0;
}
}
}
return f;
}
};
应该没啥特殊的解法吧,直接dfs就完事了。
加油加油!!