题意:给一个存有字母的二维矩阵和一个单词,问单词是否可以是二维矩阵的一条路径上的字母组成的,路径移动方向是4个方向,上下左右。
题解:dfs即可。
class Solution {
public:
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
bool dfs(vector<vector<char>>& board, string word,int i,int j)
{
if(word.length() < 1) return true;
char c = board[i][j];
int n = board.size();
int m = board[0].size();
board[i][j] = '\0';
bool flag = false;
for(int k = 0; k < 4; k++)
{
int tx = i + dir[k][0];
int ty = j + dir[k][1];
if(tx < 0 || ty < 0 || tx >= n || ty >= m || board[tx][ty] != word[0]) continue;
flag |= dfs(board,word.substr(1),tx,ty);
}
if(flag) return true;
board[i][j] = c;
return false;
}
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(board[i][j] == word[0] && dfs(board,word.substr(1),i,j))
return true;
return false;
}
};