剑指offer — 矩阵中的路径
来源:互联网 发布:js生成二维码图片 编辑:程序博客网 时间:2024/06/09 14:40
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子
java
import java.util.*;public class Solution { public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {if (matrix == null || matrix.length < rows * cols || str == null || str.length <= 0) { return false; } boolean[] visit = new boolean[rows * cols]; Arrays.fill(visit, false); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (findPath(matrix, rows, cols, str, i, j, 0, visit)) { return true; } } } return false; } private boolean findPath(char[] matrix, int rows, int cols, char[] str, int row, int col, int len, boolean[] visit) { if (len == str.length) { return true; } boolean path = false; if (row >= 0 && row < rows && col >= 0 && col < cols && matrix[row * cols + col] == str[len] && visit[row * cols + col] == false) { visit[row * cols + col] = true; len++; path = findPath(matrix, rows, cols, str, row, col + 1, len, visit) || findPath(matrix, rows, cols, str, row, col - 1, len, visit) || findPath(matrix, rows, cols, str, row + 1, col, len, visit) || findPath(matrix, rows, cols, str, row - 1, col, len, visit); if (!path) { visit[row * cols + col] = false; len--; } } return path; }}
阅读全文
0 0
- 《剑指offer》——矩阵中的路径
- 剑指offer——矩阵中的路径
- 剑指offer——矩阵中的路径
- 剑指offer—矩阵中的路径
- 剑指offer—矩阵中的路径
- 剑指offer — 矩阵中的路径
- 剑指offer--矩阵中的路径
- 《剑指offer》矩阵中的路径
- 剑指offer:矩阵中的路径
- [剑指offer]矩阵中的路径
- 剑指offer-矩阵中的路径
- 剑指offer 矩阵中的路径
- 剑指offer-矩阵中的路径
- 剑指offer-矩阵中的路径
- 剑指offer 矩阵中的路径
- [剑指offer]矩阵中的路径
- 剑指offer 矩阵中的路径
- 剑指offer --- 矩阵中的路径
- 爬取京东手机商品信息
- Spring单例对象中引用非单例对象的方式:购物车问题的解决方案
- CTF-练习平台 WriteUp
- 深入理解JVM--java内存区域分析
- C#笔记(18)MessageBox.Show自定义按钮文字
- 剑指offer — 矩阵中的路径
- 1.python学习开始
- 论文阅读-LightGBM: A Highly Efficient Gradient Boosting Decision Tree
- 用Python写堡垒机项目
- 热键管理
- hbase使用外部(非自带)zookeeper搭建伪分布式环境
- MyEclipse 2017 CI9新功能及下载地址
- 项目管理4
- 3.23节练习题