leetcode原题链接:单词搜索
题目描述
给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" 输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" 输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
和word
仅由大小写英文字母组成
解题方法:回溯。用backtrack(board, x, y, word, i, visited)表示是否存在以board[x][y]为开始节点,能找到单词word,为了防止重复兜圈查找,用visited变量保存标记当前已经访问的位置。
核心逻辑如下:
1)visited[x][y]=true,比较board[x][y]是否等于word[i],不相等直接返回false;
2) 如果board[x][y]等于word[i],则继续向上、下、左、右四个方向继续搜索word[i+1];
3)结果为: result(上) || result(下) || result(左) || result(右)
4)visited[x][y]=false 恢复状态
C++代码
#include <iostream>
#include <vector>
#include <string>
class Solution {
public:
bool exist(std::vector<std::vector<char>>& board, std::string word) {
int rnum = board.size();
int cnum = board[0].size();
std::vector<std::vector<bool>> visited(rnum, std::vector<bool>(cnum, false));
for (int x = 0; x < rnum; x++) {
for (int y = 0; y < cnum; y++) {
if (backtrack(board, x, y, word, 0, visited)) { //以(x,y)为开始节点去搜索
return true;
}
}
}
return false;
}
//判断以board(x,y)为起点是否能找到word
bool backtrack(std::vector<std::vector<char>>& board, int x, int y,
std::string word, int i, std::vector<std::vector<bool>>& visited) {
int rnum = board.size();
int cnum = board[0].size();
int word_n = word.size();
if (i == word_n) {
return true;
}
if (x < 0 || x >= rnum || y < 0 || y >= cnum) {
return false;
}
if (visited[x][y]) {//已经访问过,直接返回
return false;
}
if (board[x][y] != word[i]) { //首字母不同,直接返回
return false;
}
visited[x][y] = true;//标记为访问
bool result = false;
result = backtrack(board, x - 1, y, word, i + 1, visited) || //向上查找
backtrack(board, x + 1, y, word, i + 1, visited) || //向上
backtrack(board, x, y - 1, word, i + 1, visited) || //向左
backtrack(board, x, y + 1, word, i + 1, visited); //向右
visited[x][y] = false;
return result;
}
};