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.
For example,
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
,
-> returns true
,word =
"SEE"
,
-> returns true
,word = "ABCB"
,
-> returns false
.
代码:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int width = board[0].size();
int height = board.size();
vector<vector<bool>> used(height, vector<bool>(width, false));
bool res = false;
for (int i = 0; i < board.size(); i++){
for (int j = 0; j < board[0].size(); j++){
if (board[i][j] == word[0])
used[i][j] = true;
helper(board, 0, word, res, i, j, 0, used);
used[i][j] = false;//记住, 这里的used也要回溯。
}
}
return res;
}
// 这里的direction参数可以省略
void helper(vector<vector<char>>& board, int start, string& word, bool& res, int x, int y, int direction, vector<vector<bool>>& used){
if(res) return;//这一句太重要了, DFS + Backtracking 在搜索到第一个结果时,要break;
if (board[x][y] != word[start]) return;
if (start == word.size() - 1){
res = true;
return;
}
int width = board[0].size();
int height = board.size();
if (direction != 2 && y != 0 && !used[x][y - 1])//left 1
{
used[x][y - 1] = true;
helper(board, start + 1, word, res, x, y - 1, 1, used);
used[x][y - 1] = false;
}
if (direction != 1 && y != width - 1 && !used[x][y + 1])//right 2
{
used[x][y + 1] = true;
helper(board, start + 1, word, res, x, y + 1, 2, used);
used[x][y + 1] = false;
}
if (direction != 4 && x != 0 && !used[x - 1][y])//down 3
{
used[x - 1][y] = true;
helper(board, start + 1, word, res, x - 1, y, 3, used);
used[x - 1][y] = false;
}
if (direction != 3 && x != height - 1 && !used[x + 1][y])//up 4
{
used[x + 1][y] = true;
helper(board, start + 1, word, res, x + 1, y, 4, used);
used[x + 1][y] = false;
}
}
};
优化代码:
public class Solution {
public boolean exist(char[][] board, String word) {
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length; j++){
if(exist(board, i, j, word, 0))
return true;
}
return false;
}
private boolean exist(char[][] board, int i, int j, String word, int ind){
if(ind == word.length()) return true;
if(i > board.length-1 || i <0 || j<0 || j >board[0].length-1 || board[i][j]!=word.charAt(ind))
return false;
board[i][j]='*';
boolean result = exist(board, i-1, j, word, ind+1) ||
exist(board, i, j-1, word, ind+1) ||
exist(board, i, j+1, word, ind+1) ||
exist(board, i+1, j, word, ind+1);
board[i][j] = word.charAt(ind);
return result;
}