P1605 迷宫(dfs,洛谷,java)

洛谷链接:https://www.luogu.com.cn/problem/P1605

很基础的一道搜索题,适合入门
在这里插入图片描述
在这里插入图片描述

import java.util.Scanner;
public class Main {
    
	static int[][] map=new int[10][10];                             //地图
	static boolean[][] temp=new boolean[10][10];                    //走过的标记
	static int[] dx= {0,0,1,-1};                                  //打表
	static int[] dy= {-1,1,0,0};                                  //打表
	static int total=0,fx=0,fy=0,sx=0,sy=0,T=0,n=0,m=0,l=0,r=0;//total计数器,fx,fy是终点坐标,sx,sy是起点坐标,T是障碍总数,n,m是地图的长和宽,l,r是障碍的横坐标和纵坐标;
	
	public static void walk(int x,int y){    //定义walk
		if(x==fx && y==fy) {                 //如果到了结束坐标
			total++;                         //总数增加
			return;                          //返回,继续搜索
		}else { 
			for(int i=0;i<=3;i++) {          //0——3是左,右,下,上四个方向;
				if(temp[x+dx[i]][y+dy[i]]==false  &&  map[x+dx[i]][y+dy[i]]==1) {    //判断没有走过和没有障碍
					temp[x][y]=true;         //走过的地方打上标记;
					walk(x+dx[i],y+dy[i]);
	                temp[x][y]=false;        //还原状态;
				}
			}
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in=new Scanner(System.in);
		n=in.nextInt();    //长度
		m=in.nextInt();    //宽度
		T=in.nextInt();    //障碍个数
		
		for(int ix=1;ix<=n;ix++) {
			for(int iy=1;iy<=m;iy++) {
				map[ix][iy]=1;   //把地图刷成1
			}
		}
		sx=in.nextInt();         //起始x
		sy=in.nextInt();         //起始y
		fx=in.nextInt();         //结束x
		fy=in.nextInt();         //结束y
		
		for(int u=1;u<=T;u++) {
			l=in.nextInt();      //l,r是障碍坐标;
			r=in.nextInt();
			map[l][r]=0;
		}
		walk(sx,sy);
		System.out.println(total);
	}
}
 
 
 

发布了68 篇原创文章 · 获赞 26 · 访问量 559

猜你喜欢

转载自blog.csdn.net/weixin_44685629/article/details/104060768