[剑指Offer] 65.矩阵中的路径

题目描述

  请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如[a b c e s f c s a d e e]是3*4矩阵,其包含字符串"bcced"的路径,但是矩阵中不包含“abcb”路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

【思路】dfs尝试从每个结点开始走,走过一个结点就将其值置为'',走完之后记录是否成功,并将值恢复。

 1 class Solution {
 2 public:
 3     bool dfs(char* matrix, int rows, int cols, char* str, int i, int j){
 4         if(str == NULL || *str == ''){
 5             return true;
 6         }
 7         bool ans = false;
 8         if((i>= 0) && (i < rows) && (j >= 0) && (j < cols) && (matrix[i * cols + j] == *str)){
 9             matrix[i * cols + j] = '';
10             ans = dfs(matrix, rows, cols, str + 1, i - 1, j)
11                   ||dfs(matrix, rows, cols, str + 1, i + 1, j)
12                   ||dfs(matrix, rows, cols, str + 1, i, j - 1)
13                   ||dfs(matrix, rows, cols, str + 1, i, j + 1);
14             matrix[i * cols + j] = *str;
15         }
16         return ans;
17     }
18     bool hasPath(char* matrix, int rows, int cols, char* str)
19     {
20         for(int i = 0;i < rows;i ++){
21             for(int j = 0;j < cols;j ++){
22                 if(dfs(matrix, rows, cols, str, i, j)){
23                     return true;
24                 }
25             }
26         }
27         return false;
28     }
29 };
原文地址:https://www.cnblogs.com/lca1826/p/6588956.html