Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
ExampleGiven board =
[ "ABCE", "SFCS", "ADEE" ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
如果用bfs来解决,必须每次都搞一个新的矩阵乎哟这vector来记录当前路径上锁浏览过的点, 不能使用引用类型,否则出错;
虽然能计算,但是内存不够, 爆了~~
只能使用DFS来做, 随意必须使用引用类型来节约内存:
如果当前点符合条件, 则计算相邻的点,注意在进行下一侧迭代的时候,必须将当前的点置为#,然后DFS四个相邻点,注意,在返回
此次迭代前,必须把当前点还原,否则会出错影响其他点的DFS;
class Solution {
public:
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
bool exist(vector<vector<char> > &board, string word) {
// write your code here
if (word.size() == 0 || board.empty()) {
return false;
}
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++){
if (DFS(board, i, j, 0, word))
return true;
}
}
return false;
}
bool DFS(vector<vector<char> > &board, int i, int j, int len, string word) {
if (0 <= i && i < board.size() && 0 <= j && j < board[0].size()) {
if (len == (int)word.size() - 1 && board[i][j] == word[len]) {
return true;
}
if (board[i][j] != word[len]) {
return false;
}
//cout<<i<<" "<<j<<" "<<board[i][j]<<endl;
char c = board[i][j];
board[i][j] = '#';
bool res = DFS(board, i - 1, j, len + 1,word) ||
DFS(board, i + 1, j, len + 1,word) ||
DFS(board, i, j - 1, len + 1,word) ||
DFS(board, i, j + 1, len + 1,word);
board[i][j] = c;
return res;
} else {
return false;
}
}
};