地址 https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
地址 https://leetcode-cn.com/problems/word-search/comments/
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。 如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。 例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径 (路径中的字母用加粗标出)。 [["a","b","c","e"], ["s","f","c","s"], ["a","d","e","e"]] 但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。 示例 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 注意:本题与主站 79 题相同:https://leetcode-cn.com/problems/word-search/
解答 DFS
用了一些小技巧 比如修改board中元素为不可能相等的值 避免重复进入,但是要记得在退出当前递归层的时候恢复
class Solution { public: int addx[4] = { 1,-1,0,0 }; int addy[4] = { 0,0,1,-1 }; bool dfs(int x, int y, vector<vector<char>>& board, const string& word, int idx) { if (idx >= word.size()) return true; int m = board.size(); int n = board[0].size(); //临时修改board 防止重复进入 char backChar = board[x][y]; board[x][y] = '#'; for (int i = 0; i < 4; i++) { int newx = x + addx[i]; int newy = y + addy[i]; if (newx >= 0 && newx < m && newy >= 0 && newy < n && board[newx][newy] == word[idx]) { if (dfs(newx, newy, board, word, idx + 1)) return true; } } //还原 board[x][y] = backChar; return false; } bool exist(vector<vector<char>>& board, string word) { if (board.empty() || board[0].empty()) return false; int m = board.size(); int n = board[0].size(); for (int x = 0; x < m; x++) { for (int y = 0; y < n; y++) { if (board[x][y] == word[0]) { if (dfs(x, y, board, word, 1) == true) return true; } } } return false; } };