题目大意:求一个字符串是否存在于由矩阵中,只能沿着上下左右四个方向查找
思路:深度遍历
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
int m = board.size();
int n = -1;
if(m > 0) {
n = board[0].size();
}
if(m == 0 || n == 0) {
if(word.empty()) {
return true;
} else {
return false;
}
}
vector<vector<bool> > grid(m, vector<bool>(n, false));
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(existAssist(board, grid, i, j, word, 0)) {
return true;
}
}
}
return false;
}
private:
bool existAssist(vector<vector<char> > &board, vector<vector<bool> > &grid, int i, int j, const string& word, int index) {
if(index >= word.size()) {
return true;
}
if(i >= 0 && i < board.size() && j >= 0 && j < board[0].size() && !grid[i][j] && board[i][j] == word[index]) {
grid[i][j] = true;
if(existAssist(board, grid, i + 1, j, word, index + 1)) {
return true;
}
if(existAssist(board, grid, i - 1, j, word, index + 1)) {
return true;
}
if(existAssist(board, grid, i, j + 1, word, index + 1)) {
return true;
}
if(existAssist(board, grid, i, j - 1, word, index + 1)) {
return true;
}
grid[i][j] = false;
}
return false;
}
};