0
点赞
收藏
分享

微信扫一扫

P1605 迷宫(java的看着篇就完事了)

言午栩 2022-04-14 阅读 39

题目背景

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

题目描述

输入格式

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

输出格式

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

输入输出样例

输入 #1

输出 #1

	import java.util.*;
	public class Main {
		static int [][] arr=new int [10][10]; //建图
		static boolean [][] vis=new boolean [10][10]; //记忆
		static int [] dx= {-1,1,0,0}; //上下左右
		static int [] dy= {0,0,-1,1};
		static int n,m; //行列
		static int t;//障碍数
		static int sx,sy,fx,fy;// sx sy 起点坐标 fx fy终点坐标
		static int ant;
	    public static void main(String[] args)   {
	    	//大水题
	    	Scanner scanner=new Scanner(System.in);
	    	n=scanner.nextInt();
	    	m=scanner.nextInt();
	    	t=scanner.nextInt();
	    	for (int i = 1; i <=n; i++) {
				for (int j = 1; j <=m; j++) { //开始建图 把图全部变为0
					arr[i][j]=1;
				}
			}
			sx=scanner.nextInt(); //起点
			sy=scanner.nextInt(); //起点
			fx=scanner.nextInt(); //终点
			fy=scanner.nextInt(); //终点
			for (int i = 1; i <=t; i++) { //障碍不只一个呢
				arr[scanner.nextInt()][scanner.nextInt()]=0;//建立障碍下标 障碍变为9
			}
			vis[sx][sy]=true; //初始位置标记为访问
			dfs(sx, sy); //放入起点坐标开始dfs
			System.out.print(ant);
		}
	   
	    public static void dfs(int x,int y) { //开始dfs
			if (x==fx && y==fy) { //退出条件就是走到终点
				ant++; 
				return; 
			}
		
		        for (int i = 0; i <4; i++) { //四个方向
		        	int tx=dx[i]+x; int ty=dy[i]+y;
		        	if (tx<1 || ty<1 || tx>n || ty>m) {//防止越界
						continue;
					}
		        	if (!vis[tx][ty] && arr[tx][ty]==1) { //未访问过 并且不是障碍
		        		vis[tx][ty]=true; //进入if标记访问
			        	dfs(tx, ty); 
			        	vis[tx][ty]=false; //回溯
				}
		    }
		}
	}

 

举报

相关推荐

0 条评论