题目地址:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的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
解题思路
矩阵搜索问题一般采用回溯法,或者DFS。这里我们以word="ABCCEE"为例说明,我们先采用暴力搜索的方法寻找到word子串中第一个字母A,然后按照深度优先搜索方法DFS查找是否有和word匹配的字符串,如果找到了则直接返回true,否则,继续寻找下一个A。为了避免重复搜索,我们将搜索过的字符设置为0。
程序源码
DFS
class Solution { public: bool exist(vector<vector<char>>& board, string word) { if(board.size() == 0) return false; int rows = board.size(); int cols = board[0].size(); for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { if(dfs(board, word, i, j, 0)) { return true; } } } return false; } bool dfs(vector<vector<char>>& board, string &word, int i, int j, int word_len) { if(i >= board.size() || j >= board[0].size() || word_len >= word.size() || word[word_len] != board[i][j]) return false; if(word[word_len] == board[i][j] && word_len == word.size() - 1) return true; char ch = board[i][j]; board[i][j] = '0'; bool flag = dfs(board, word, i - 1, j, word_len + 1) || dfs(board, word, i + 1, j, word_len + 1) || dfs(board, word, i, j - 1, word_len + 1) || dfs(board, word, i, j + 1, word_len + 1); board[i][j] = ch; //避免重复进入 return flag; } };
巧妙解法
class Solution { public: int x[4] = {0,0,-1,1}; //左右上下顺序 int y[4] = {-1,1,0,0}; //左右上下顺序 int rows, cols; bool exist(vector<vector<char>>& board, string word) { if(board.size() == 0) return false; rows = board.size(); cols = board[0].size(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (board[i][j] == word[0]) { if (dfs(board,word,i,j,1)) return true; } } } return false; } bool dfs(vector<vector<char>>& board,string word,int i,int j,int word_len) { if (word_len == word.size()) return true; char ch = board[i][j]; board[i][j] = '0'; for (int k = 0; k < 4; k++) { int dfs_x = x[k] + i; int dfs_y = y[k] + j; if (dfs_x >= 0 && dfs_x < rows && dfs_y >= 0 && dfs_y < cols && word[word_len] == board[dfs_x][dfs_y]) { if (dfs(board,word,dfs_x,dfs_y,word_len + 1)) return true; } } board[i][j] = ch; return false; } };