12、矩阵中的路径
2018-03-30 14:33
399 查看
public class Solution { boolean hasPath = false; public boolean hasPath(char[] matrix, int rows, int cols, char[] str) { //对矩阵的每个点进行search,查到了路径就返回true for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) { boolean[] visited = new boolean[rows*cols]; search(matrix,rows,cols,i,j,0,str,visited); if(hasPath == true) return true; } } return false; } public void search(char[] matrix,int rows, int cols,int row,int col,int k,char[] str,boolean[] visited) { //如果该点坐标没有越界且没被查询过 if((row>-1) && (row<rows) && (col>-1) && (col<cols) && (visited[row*cols+col]==false)) { if(matrix[cols*row+col]==str[k]) { //如果是字符串的最后一个字符且相等,代表包含该路径 if(k==str.length-1) { hasPath=true; return; } visited[cols*row+col] = true; //查询该点上下左右的点 search(matrix,rows,cols,row,col-1,k+1,str,visited); search(matrix,rows,cols,row,col+1,k+1,str,visited); search(matrix,rows,cols,row-1,col,k+1,str,visited); search(matrix,rows,cols,row+1,col,k+1,str,visited); } } } }
相关文章推荐
- 剑指Offer_12_矩阵中的路径(参考问题:马踏棋盘)
- 剑指Offer面试题12:矩阵中的路径
- 【剑指**】12.矩阵中的路径
- 《剑指offer》面试题12:矩阵中的路径
- 【剑指offer】面试题12:矩阵中的路径
- 剑指offer2 问题12 矩阵中的路径 Java实现
- 剑指Offer(12)矩阵中的路径
- 剑指offer面试题12:矩阵中的路径Java实现版
- 剑指offer--面试题12:矩阵中的路径
- 《剑指offer》12.矩阵中的路径
- 剑指offer面试题12:矩阵中的路径(java实现)
- 输出从矩阵左上角到右下角的所有路径
- 矩阵中的路径—递归
- 矩阵的最小路径和
- 动态规划3:矩阵最小路径和问题
- Floyed算法求最短路径及其长度矩阵和路径矩阵
- 矩阵最小路径和练习
- 牛客网剑指offer-矩阵中的路径
- JAVA回溯, 实现 矩阵中的路径寻找问题
- 剑指offer-矩阵中的路径