洛谷 P1605 迷宫

Posted 爱敲代码的三毛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了洛谷 P1605 迷宫相关的知识,希望对你有一定的参考价值。

题目

给定一个N*M方格的迷宫,迷宫里有T处障碍,障碍处不可通过。给定起点坐标和终点坐标,问: 每个方格最多经过1次,有多少种从起点坐标到终点坐标的方案。在迷宫中移动有上下左右四种方式,每次只能移动一个方格。数据保证起点上没有障碍。

输入格式

第一行N、M和T,N为行,M为列,T为障碍总数。第二行起点坐标SX,SY,终点坐标FX,FY。接下来T行,每行为障碍点的坐标。

输出格式

给定起点坐标和终点坐标,问每个方格最多经过1次,从起点坐标到终点坐标的方案总数。

思路

dfs直接搜索当前位置的上下左右,搜索过后就标记已经搜索
如果有一条路到达了终点,计数就++

代码

import java.util.Scanner;

public class Main 
    static int[][] upDownLeftRight = -1,0,1,0,0,-1,0,1;
    static int count = 0;
    static int row;
    static int col;
    public static void dfs(int[][] maze, int startX, int startY, int endX, int endY) 
        // 标记已经访问
        maze[startX][startY] = 1;
        if (startX == endX && startY == endY) 
            count++;
            return;
        

        for (int i = 0; i < 4; i++) 
            int newX = startX + upDownLeftRight[i][0];
            int newY = startY + upDownLeftRight[i][1];
            // 行和列是从1开始
            if (newX <= 0 || newX > row || newY <= 0 || newY > col || maze[newX][newY] == 1) 
                continue;
            
            dfs(maze, newX, newY, endX, endY);
            // 回溯
            maze[newX][newY] = 0;
        
    
    public static void main(String[] args) 
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int t = sc.nextInt();

        int startX = sc.nextInt();
        int startY = sc.nextInt();
        int endX = sc.nextInt();
        int endY = sc.nextInt();

        row = n;
        col = m;
        int[][] maze = new int[n+1][m+1];
        for (int i = 0; i < t; i++) 
            int x = sc.nextInt();
            int y = sc.nextInt();
            maze[x][y] = 1;
        
        dfs(maze,startX,startY,endX,endY);
        System.out.println(count);
    

开发者涨薪指南 48位大咖的思考法则、工作方式、逻辑体系

以上是关于洛谷 P1605 迷宫的主要内容,如果未能解决你的问题,请参考以下文章

洛谷 P1605 迷宫

P1605 迷宫

P1605 迷宫

洛谷 P1605 迷宫题解

洛谷P1309——迷宫(傻瓜DFS)

1605 迷宫