【剑指offer】矩阵中的路径

题目描述

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

解题思路

  1. 从0,0点开始,判断从该点出发有没有符合条件的路径;
  2. 递归判断路径是否符合,从该点出发有4条路径,分别判断,有一条符合就返回true。

我的代码

import java.util.ArrayList;
public class Solution {
    private ArrayList<Integer> xAxis = new ArrayList<>();
    private ArrayList<Integer> yAxis = new ArrayList<>();
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        if(str.length == 0 || matrix.length == 0 || matrix.length < str.length) return false;
        int i = 0, j = 0;
        while(i < rows){
            j = 0;
            while(j < cols){
                if(isPath(matrix, rows, cols, str, i, j, 0)) return true;
                j++;
            }
            i++;
        }
        return false;
    }
    private boolean contains(int row, int col){
        for(int i = 0; i < xAxis.size(); i++){
            if(row == xAxis.get(i) && col == yAxis.get(i)) return true;
        }
        return false;
    }
    private boolean isPath(char[] matrix, int rows, int cols, char[] str, int row, int col, int strIndex){
        if(strIndex >= str.length) return false;
        if(strIndex == str.length - 1 && matrix[row * cols + col] == str[strIndex]) return true;
        if(matrix[row * cols + col] != str[strIndex]) return false;
        xAxis.add(row);
        yAxis.add(col);
        boolean res = false;
        // 左
        if(col > 0 && !contains(row, col - 1)){
            res = res || isPath(matrix, rows, cols, str, row, col - 1, strIndex + 1);
        } 
        // 右
        if(col < cols - 1 && !contains(row, col + 1)){
            res = res || isPath(matrix, rows, cols, str, row, col + 1, strIndex + 1);
        }
        // 上
        if(row > 0 && !contains(row - 1, col)){
            res = res || isPath(matrix, rows, cols, str, row - 1, col, strIndex + 1);
        }
        // 下
        if(row < rows - 1 && !contains(row + 1, col)){
            res = res || isPath(matrix, rows, cols, str, row + 1, col, strIndex + 1);
        }
        xAxis.remove(xAxis.size() - 1);
        yAxis.remove(yAxis.size() - 1);
        return res;
    }
}
发布了77 篇原创文章 · 获赞 1 · 访问量 5370

猜你喜欢

转载自blog.csdn.net/u010659877/article/details/104096330