LeetCode: 79. Word Search
LeetCode: 79. Word Search
题目描述
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
.
题目大意: 求在二维数组 board
中能否找出字符串 word
, 要求数组中每个位置的字母只能用一次。
解题思路 —— 深度搜索(DFS)
对匹配上 word
第一个字母的位置进行深度搜索,依次找到匹配下一个字母的位置。将搜索过的位置标记为负,以防止重复使用同一个位置的字母。如果 word
能匹配完, 则返回 true
, 否则返回 false
。
AC 代码
class Solution {
private:
// exist 函数的辅助函数: 判断从 board 的 (x, y) 坐标开始, 能否找到 word
bool existRef(int x, int y, vector<vector<char>>& board, string word)
{
if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size() || word.empty())
{
return false;
}
// 如果当前位置和 word 首字母不匹配, 则表示该路径不能匹配 word
if(board[x][y] != word.front())
{
return false;
}
// 最后一个字母已匹配
if(word.size() == 1) return true;
// 枚举四个方向
const static int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
for(int i = 0; i < 4; ++i)
{
int tx = x + directions[i][0];
int ty = y + directions[i][1];
if(tx < 0 || ty < 0 || tx >= board.size() || ty >= board[0].size())
{
continue;
}
board[x][y] = -board[x][y]; // 标记
if(existRef(tx, ty, board, word.substr(1, word.size()-1)))
{
return true;
}
board[x][y] = -board[x][y]; // 取消标记
}
return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
for(int i = 0; i < board.size(); ++i)
{
for(int j = 0; j < board[i].size(); ++j)
{
if(existRef(i, j, board, word))
{
return true;
}
}
}
return false;
}
};