题目要求
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.
给定一个二维字符数组和一个字符串,判断字符串能不能通过在二维数组中沿着水平和垂直两种方向拼出来,同一个位置上的字符只能用一次,如果可以则返回TRUE,不能则返回false。
解题思路
这又是一个典型的深搜,用两层for循环,去找寻入口,若找到满足条件的入口(board[i][j] = word[0]),则在board[i][j]的四周找寻满足条件的下一个字符。注意,同一个位置上的字符只能用一次,因此,需要一个visited数组来保存二维数组的访问状态。
代码
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();
if (m == 0 || n == 0){
return false;
}
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
vector<vector<bool>> visited(m,vector<bool>(n,false));
if (dfs(board,i,j,word,visited) == true){//如果找到,则返回TRUE。
return true;
}
}
}
return false;
}
bool dfs(vector<vector<char>>& board, int i, int j, string word, vector<vector<bool>> & visited){
if (word.length() == 0){//找到,匹配成功
return true;
}
if (!(i>=0 && i<board.size()) || !(j>=0 && j<board[0].size())){
return false;
}
if (board[i][j] != word[0]){
return false;
}
else if (visited[i][j] == false){
visited[i][j] = true;
bool res;
res = dfs(board,i+1,j,word.substr(1),visited);//在i,j的上下左右找寻。
if (!res) res = dfs(board,i-1,j,word.substr(1),visited);
if (!res) res = dfs(board,i,j-1,word.substr(1),visited);
if (!res) res = dfs(board,i,j+1,word.substr(1),visited);
if (res){
return res;
}else{
visited[i][j] = false;
return res;
}
}else{
return false;
}
}
};
结果
87 / 87 test cases passed.
Status: Accepted
Runtime: 868 ms