剑指 Offer 12. 矩阵中的路径

题目链接

  • 题目类似于迷宫的搜索。
  • 需要注意的是,需要首先判断起始搜索的位置,可能有多个起点,都需要一一尝试。
  • 每轮迭代的时候记得将是否遍历标记数组还原为未遍历的状态。
package com.walegarrett.offer;

/**
* @Author WaleGarrett
* @Date 2020/12/9 9:09
*/ import java.util.Arrays; /**
* [["a","b","c","e"],
* ["s","f","c","s"],
* ["a","d","e","e"]]
* 矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
* 1 <= board.length <= 200
* 1 <= board[i].length <= 200
*/
public class Offer_12 {
private String word;
private boolean[][] travel;
private final int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public boolean exist(char[][] board, String word) {
if(board == null)
return false;
if(word.length() == 0)
return true;
this.word = word;
travel = new boolean[board.length][board[0].length];
for(int i =0; i< board.length; i++){
for(int j =0; j< board[0].length; j++){
travel[i][j] = false;
}
}
for(int i =0; i< board.length; i++){
int len = board[0].length;
for(int j =0; j< len; j++){
if(board[i][j] != word.charAt(0))
continue;
travel[i][j] = true;
if(findPath(board, 0, i, j)){
return true;
}
travel[i][j] = false;
}
}
return false;
}
public boolean findPath(char[][] board, int pos, int x, int y){
if(pos >= word.length() - 1){
if(board[x][y] == word.charAt(pos))
return true;
return false;
}
//遍历四个方向
for(int i = 0; i< 4; i++){
int dx = x + direction[i][0];
int dy = y+ direction[i][1];
if(dx>=0 && dy>=0 && dx<board.length && dy< board[0].length && !travel[dx][dy]){
if(board[dx][dy] == word.charAt(pos + 1)){
travel[dx][dy] = true;
if(findPath(board, pos+1, dx, dy)){
travel[dx][dy] = false;
return true;
}else travel[dx][dy] = false;
}
}
}
return false;
}
}

最新文章

  1. listener does not currently know of SID项目部署报数据库错
  2. 浅谈session/cookie
  3. 使用JUnit4进行java单元测试
  4. MySQL 之 query cache
  5. Failure [INSTALL_FAILED_SHARED_USER_INCOMPATIBLE]
  6. saltstack实战4--综合练习3
  7. [Python笔记]第十一篇:面向对象
  8. 贝叶斯网络基础(Probabilistic Graphical Models)
  9. Codeforces Round #367 (Div. 2) D. Vasiliy&#39;s Multiset
  10. axis-运行bat报错问题
  11. Python计算一个项目中含有的代码行数
  12. 社交系统ThinkSNS+ APP更新至V0.8.3---新增打赏、用户认证
  13. React Native开发工具Nuclide使用
  14. Codeforces1097D. Makoto and a Blackboard(数论+dp+概率期望)
  15. DockerFile解析
  16. {MySQL的库、表的详细操作}一 库操作 二 表操作 三 行操作
  17. Cocos2d比较好的博客
  18. KindEditor 上传文件 在Asp.net中的使用
  19. Django,COOKIES,SESSION完成用户登入
  20. REPEAT_BYTE(x)宏

热门文章

  1. GCD HDU - 1695 容斥原理(复杂度低的版本)
  2. Intelligent IME HDU - 4287 字典树
  3. CQRS+Event Sourcing
  4. PowerShell随笔1---背景
  5. Spring Cloud实战 | 第十一篇:Spring Cloud Gateway 网关实现对RESTful接口权限控制和按钮权限控制
  6. docker+prom+grafana+altermanager
  7. kubernetes实战-交付dubbo服务到k8s集群(六)使用blue ocean流水线构建dubbo-consumer服务
  8. Leetcode(712)-账户合并
  9. php性能分析利器:xhprof
  10. git tag All In One