矩阵中的路径(Java实现)


public class E12FindPath {
    //与C语言不同,此处用全局静态变量用作递归中比较字符的指针
    private static int pathLength = 0;

    public static boolean hasPath(char[] matrix, int rows, int cols, char[] str){
        if(matrix == null || str == null || rows < 1 || cols < 1)
            return false;

        //布尔数组用于标记矩阵元素是否已被访问
        boolean[] visited = new boolean[rows * cols];
        for (boolean bool : visited)
            bool = false;

        for (int row = 0; row < rows; row++){
            for (int col = 0; col < cols; col++){
                //每次都重置指针
                pathLength = 0;
                if (hasPathCore(matrix, rows, cols, str,
                        row, col,visited))
                    return true;
            }
        }
        return false;
    }

    private static boolean hasPathCore(char[] matrix, int rows, int cols, char[] str,
                                int row, int col, boolean[] visited){
        //递归终止条件
        if (str.length == pathLength)
            return true;

        boolean hasPath = false;
        if (row >= 0 && row < rows && col >= 0 && col < cols
                && !visited[row * cols + col] && matrix[row * cols + col] == str[pathLength]){
            pathLength++;
            visited[row * cols + col] = true;
            //易犯错误,采用row++,将会改变row本身的值
            hasPath = hasPathCore(matrix, rows, cols, str,
                    row + 1, col, visited) ||
                    hasPathCore(matrix, rows, cols, str, row - 1, col, visited) ||
                    hasPathCore(matrix, rows, cols, str, row, col + 1, visited) ||
                    hasPathCore(matrix, rows, cols, str, row, col - 1, visited);
            //此路径不符合则回溯
            if (!hasPath){
                pathLength--;
                visited[row * cols + col] = false;
            }
        }
        return hasPath;
    }

    //测试用例
    public static void main(String[] args){
        char[] matrix = {'a', 'b', 'c', 'd', 'e', 'f'};
        char[] str = {'b', 'e', 'd'};
        System.out.println(E12FindPath.hasPath(matrix, 2, 3, str));

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值