首页 > 其他分享 >[Algorithm] Path maze solver - recursive

[Algorithm] Path maze solver - recursive

时间:2023-07-22 19:34:40浏览次数:34  
标签:curr recursive solver end maze return path Path const

// Base case
// 1. Off the map
// 2. Hit a wall
// 3. Already visited
// 4. It's the end

const dirs = [
    [1, 0], //top
    [0, 1], //right
    [-1, 0], //bottom
    [0, -1], //left
];

function walk(
    maze: string[],
    wall: string,
    curr: Point,
    end: Point,
    seen: boolean[][],
    path: Point[],
): boolean {
    // Base case
    // 1. Off the map
    if (
        curr.x < 0 ||
        curr.x >= maze[0].length ||
        curr.y < 0 ||
        curr.y >= maze.length
    ) {
        return false;
    }

    // 2. Hit a wall
    if (maze[curr.y][curr.x] === wall) {
        return false;
    }

    // 3. Already visited
    if (seen[curr.y][curr.x]) {
        return false;
    }

    // 4. It's the end
    if (curr.y === end.y && curr.x === end.x) {
        path.push(curr);
        return true;
    }

    // do Recurse
    // pre
    // update seen array
    seen[curr.y][curr.x] = true;
    // add next point to the path
    path.push(curr);

    // recurse
    for (let i = 0; i < dirs.length; i++) {
        const [y, x] = dirs[i];
        if (
            walk(maze, wall, { y: curr.y + y, x: curr.x + x }, end, seen, path)
        ) {
            return true;
        }
    }

    // post
    // it's not the correct path, remove it
    path.pop();
    return false;
}

export default function solve(
    maze: string[],
    wall: string,
    start: Point,
    end: Point,
): Point[] {
    const seen: boolean[][] = Array.from({ length: maze.length }, () =>
        Array.from({ length: maze[0].length }, () => false),
    );
    const path: Point[] = [];
    walk(maze, wall, start, end, seen, path);
    return path;
}

 

Test:

import maze_solver from "@code/MazeSolver";

test("maze solver", function () {
    const maze = [
        "xxxxxxxxxx x",
        "x        x x",
        "x        x x",
        "x xxxxxxxx x",
        "x          x",
        "x xxxxxxxxxx",
    ];

    const mazeResult = [
        { x: 10, y: 0 },
        { x: 10, y: 1 },
        { x: 10, y: 2 },
        { x: 10, y: 3 },
        { x: 10, y: 4 },
        { x: 9, y: 4 },
        { x: 8, y: 4 },
        { x: 7, y: 4 },
        { x: 6, y: 4 },
        { x: 5, y: 4 },
        { x: 4, y: 4 },
        { x: 3, y: 4 },
        { x: 2, y: 4 },
        { x: 1, y: 4 },
        { x: 1, y: 5 },
    ];

    // there is only one path through
    const result = maze_solver(maze, "x", { x: 10, y: 0 }, { x: 1, y: 5 });
    expect(drawPath(maze, result)).toEqual(drawPath(maze, mazeResult));
});

function drawPath(data: string[], path: Point[]) {
    const data2 = data.map((row) => row.split(""));
    path.forEach((p) => {
        if (data2[p.y] && data2[p.y][p.x]) {
            data2[p.y][p.x] = "*";
        }
    });
    return data2.map((d) => d.join(""));
}

 

标签:curr,recursive,solver,end,maze,return,path,Path,const
From: https://www.cnblogs.com/Answer1215/p/17574061.html

相关文章

  • SLF4J: Class path contains multiple SLF4J bindings报错,logback-classic.jar与slf4j
    1.问题:控制台一直报错: 1SLF4J:ClasspathcontainsmultipleSLF4Jbindings.2SLF4J:Foundbindingin[jar:file:/logback-classic/1.1.11/logback-classic-1.1.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]3SLF4J:Foundbindingin[jar:file:/slf4j/slf4j-log......
  • pathchk
    pathchk检查文件中不可移植的部分补充说明pathchk命令用来检查文件中不可移植的部分。语法pathchk(选项)(参数)选项-p:检查大多数的POSIX系统;-P:检查空名字和“-”开头的文件;--portability:检查所有的POSIX系统,等同于“-P-p”选项;--help:显示帮助;--wersion:显示版本号。......
  • ASP.NET mappath
    ASP.NET使用mappath获取文件路径在ASP.NET开发中,我们经常需要获取服务器上的文件路径,以便进行文件操作或者读取文件内容。而在ASP.NET中,我们可以使用mappath方法来获取服务器上的文件路径。本文将介绍mappath的使用方法,并提供代码示例。什么是mappath?mappath是ASP.NET中的一个方......
  • WARN common.Util: Path /E:/hadoop/hadoop-2.2.0/data/namenode should be speci
    如何解决"WARNcommon.Util:Path/E:/hadoop/hadoop-2.2.0/data/namenodeshouldbespecifiedasaURIwhoseschemeandauthorityare'null'.Theuriwereceivedwas:/E:/hadoop/hadoop-2.2.0/data/namenode"错误作为一名经验丰富的开发者,我将指导你如何解决这个错误。首......
  • kubectl apply -f mysql.yaml error: the path "mysql.yaml" does not exist
    问题解决:kubectlapply-fmysql.yamlerror:thepath"mysql.yaml"doesnotexist在使用Kubernetes进行容器编排时,我们经常使用kubectl命令行工具与Kubernetes集群进行交互。其中,kubectlapply命令用于创建或更新Kubernetes资源的配置文件。然而,有时在执行kubectlapply-fmys......
  • HDU 5492 Find a path 题解
    Description在矩阵中,找一条到从\((1,1)\)到\((n,m)\)(只能向上,右走)的路径,使路径上方差最小。输出方差平方乘\(n+m-1\)的结果。对于所有数据,\(1\leqn,m,A_{i,j}\leq30\)。Solution设路径上的数为\(A_{1},A_{2},A_{3},\cdots,A_{n+m-1}\),\(\overline{A}\)为其平均数,则答......
  • Go安装的设置问题:GOROOT,GOPATH
    Mac下使用Google官方的Go语言安装包:https://code.google.com/p/go/downloads/list 安装的Go,会自动把/usr/local/go/bin目录加入PATH中。这样我们直接在控制台就可以执行go语言的一些命令。http://golang.org/cmd/go/#hdr-GOPATH_environment_variable 下面使用export命令看到......
  • HandlerMethodArgumentResolver方法参数解析器的使用
    一、使用场景介绍HandlerMethodArgumentResolver,中文称为方法参数解析器,是SpringWeb(SpringMVC)组件中的众多解析器之一,主要用来对Controller中方法的参数进行处理。在一般的接口调用场景下,每次调用Controller都需要检查请求中的token信息,并根据token还原用户信息,然后将用户信息封......
  • java @path
    实现Java@Path注解的步骤作为一名经验丰富的开发者,你即将向一位刚入行的小白解释如何实现Java@Path注解。这个注解用于标识RESTfulAPI中的路径。步骤概览下面是实现Java@Path注解的步骤概览,我们将通过表格的形式展示每个步骤所需的操作:步骤操作代码1.引入相关依......
  • ::before中的元素无法用xpath进行定位
    上述代码中定位知道了这个按钮,使用常规的xpath无法定位到,查了很多资料有说什么js转的等等,都不对,结果试了试使用CSS_SELECTOR进行定位,就可以定位到。使用CSS选择器定位弹窗中的"知道了"按钮`button=WebDriverWait(driver,10).until(EC.presence_of_element_located((By.CS......