P1605 迷宫(java题解)

题目链接:迷宫 - 洛谷

思路

根据递归的特性,变化参数(变化位置),每到一个点就根据下右上左的方式去判断此路是否是通的,如果可以(只要其中有一个方位的位置的通的就算跑通了)跑通就在当前点在进行四个位置的搜索。当跑出界外无路可走的时候,就返回上一个点(进行下一个位置判断是否通,把当前跑通点设置为没有被走过,方便下一次从别的地方到这个点)

小坑

根据1≤N,M≤5我们可以知道地图大概的范围是5以上。

注意入口位置不是边界位置,障碍物不能走。

dfs(int x, int y){
    //...
    dfs(x+dx[i],y+dy[i]);
    //...
    vis[x][y]
}

AC代码

import java.util.Scanner;

public class Main {
    public  static int[][] matrix=new int[6][6];  //迷宫的位置
    public  static boolean[][] vis=new boolean[6][6];//是否访问的标志
    public  static int sum=0;
    public  static int dx[]={1,0,-1,0};
    public  static int dy[]={0,1,0,-1};
    public static int sx = 0,sy = 0;
    public static int fx = 0,fy = 0;
    public static int a = 0,b = 0;
    public static int n = 0,m = 0;
    public static void dfs(int x,int y){
//        System.out.println("("+x+","+y+")");
//        System.out.println("fx="+fx+", fy="+fy);
        if(x==fx && y==fy)
        {
            sum++;
            return;
        }
        else {

            for (int i = 0; i <4 ; i++) {

                int newx =x+dx[i];
                int newy =y+dy[i];

                // if() newx newy不能越界 不能是阻碍物 不是访问过的
                //只是说入口在sx,sy 不是边界条件在入口
                if((newx >= 1 && newx <= n && newy >= 1 && newy <= m ) && !vis[newx][newy] && matrix[newx][newy] == 0){
//                    System.out.println("("+newx+","+newy+")");
                    vis[x][y]=true;
                    dfs(newx,newy);
                    vis[x][y]=false;
                }
            }
//            System.out.println();
        }
//        System.out.println();
    }


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        int t = sc.nextInt();

        sx = sc.nextInt();
        sy = sc.nextInt();
        fx = sc.nextInt();
        fy = sc.nextInt();

        for (int i = 1; i <=n ; i++) {
            for(int j = 1; j<=m; j++){
                matrix[i][j] = 0;
            }
        }

        for (int k = 1; k <= t ; k++) {
            a = sc.nextInt();
            b = sc.nextInt();
            matrix[a][b] = 1;
        }
        dfs(sx,sy);
        System.out.println(sum);
    }
}

总结

只要动脑子,没有解决不了的事情

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值