题目
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.
思路
利用递归,每次寻找某位置的上下左右是否与word的下一个值相同,如果相同,抹去该位置的值以防走重复的路,然后进入下一次递归,如果递归返回的结果为false,则恢复该位置的值,并且对下一个位置(上下左右)进行递归。
代码
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (board.size() == 0 && word.size() != 0) {
return false;
} else if (board.size() == 0 && word.size() == 0) {
return true;
}
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j] == word[0]) {
board[i][j] = ' ';
if (helper(board, i, j, word, 1)) {
return true;
}
board[i][j] = word[0];
}
}
}
return false;
}
bool helper(vector<vector<char>> board, int i, int j, string word, int index) {
if (index == word.size()) {
return true;
}
if (j+1 < board[0].size() && board[i][j+1] == word[index]) {
board[i][j+1] = ' ';
if (helper(board, i, j+1, word, index+1)){
return true;
}
board[i][j+1] = word[index];
}
if (j-1 >= 0 && board[i][j-1] == word[index]) {
board[i][j-1] = ' ';
if (helper(board, i, j-1, word, index+1)){
return true;
}
board[i][j-1] = word[index];
}
if (i-1 >= 0 && board[i-1][j] == word[index]) {
board[i-1][j] = ' ';
if (helper(board, i-1, j, word, index+1)){
return true;
}
board[i-1][j] = word[index];
}
if (i+1 < board.size() && board[i+1][j] == word[index]) {
board[i+1][j] = ' ';
if (helper(board, i+1, j, word, index+1)){
return true;
}
board[i+1][j] = word[index];
}
return false;
}
};