题目:
给定一个 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","d"]], word = "abcd"
输出:false
提示:
1 <= board.length <= 200
1 <= board[i].length <= 200
board 和 word 仅由大小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
迷宫问题,做烂了,找到第一个字母的位置,上下左右四个方向去做回溯,找满直接返回,之前还做过三维的,一个道理
代码:
class Solution {
public:
bool isFind = false;
void find(int x, int y, vector<vector<char>>& board, string word, int index) {
if (!word[index] || x >= board.size() || y >= board[0].size() || x < 0 || y < 0 || isFind || board[x][y] != word[index]) {
return;
}else {
if (index == word.length() - 1) {
isFind = true;
return;
}
board[x][y] = '\0';
find(x + 1, y, board, word, index + 1);
find(x - 1, y, board, word, index + 1);
find(x, y + 1, board, word, index + 1);
find(x, y - 1, board, word, index + 1);
}
board[x][y] = word[index];
}
bool exist(vector<vector<char>>& board, string word) {
if (!word.length()) {
return true;
}
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
find(i, j, board, word, 0);
if (isFind) {
return isFind;
}
}
}
return isFind;
}
};
备注:
不知道为啥时间复杂度和空间复杂度排名都很低,看了一下标准答案的写法也跟我差不多,算了,算法没错能过就行