剑指offer 65. 矩阵中的路径

65. 矩阵中的路径

题目描述

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

 1 import java.util.Arrays;
 2 public class Solution {
 3     public boolean flag = false;
 4 
 5     public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
 6     {
 7         boolean[] vis = new boolean[rows * cols];
 8 
 9 
10         // 遍历这个矩阵,如果元素等于str的第一个字符,进入dfs遍历,一次遍历成功即可退出循环
11         for(int i = 0; i < rows; i++){
12             for(int j = 0; j < cols; j++){
13                 if(matrix[i* cols + j] == str[0]){
14                     Arrays.fill(vis, false);
15                     // vis[i][j] = true;
16                     dfs(matrix, rows, cols, i, j, vis, str, 0);
17                     if(flag)
18                         return flag;
19                 }
20             }
21         }
22         return false;
23     }
24     public int[][] dir = {
25             {0, 1}, {0, -1}, {1, 0}, {-1, 0}
26     };
27 
28 
29     // dfs遍历
30     public void dfs(char[] matrix, int rows, int cols, int row, int col, boolean[] vis,char[] str, int nowIndex){
31         vis[row * cols + col] = true;
32         nowIndex++;
33         if(nowIndex >= str.length){
34             flag = true;
35             return;
36         }
37         // 遍历四个方向
38         for(int i = 0; i < 4; i++){
39             int newRow = dir[i][0] + row;
40             int newCol = dir[i][1] + col;
41             if(judgeBorder(newRow, newCol,rows, cols) && str[nowIndex] == matrix[newRow * cols + newCol]
42             && vis[newRow * cols + newCol] == false){
43                 dfs(matrix, rows, cols, newRow, newCol, vis, str, nowIndex);
44             }
45         }
46 
47     }
48 
49     // 判断下标是否越界
50     public boolean judgeBorder(int row, int col, int rows, int cols){
51         if(row >= 0 && row < rows && col >= 0 && col < cols)
52             return true;
53         return false;
54     }
55 }
原文地址:https://www.cnblogs.com/hi3254014978/p/12669955.html