java之迷宫

题目描述
迷宫包含n行m列个小方格,0表示可通行,1表示不可通行。在迷宫的某一位置只能向东南西北四个方向移动。
问题:判断迷宫两点之间是否有路径

输入
第一行为n和m,逗号分隔
从第2行到第1+n行,每行一个由0和1组成的长度为m的字符串,代表迷宫的结构
第2+n行 数字k,代表要判断的点对个数
第3+n行到2+n+2k行,每行一个坐标代表点

输出
按照顺序判断点对是否可达,输出true或者false

样例输入
4 15
110001001111110
101001111101111
010100011101111
111101000000001
4
1 3
3 7
1 7
1 8
1 7
3 7
4 5
4 7
样例输出
true
true
false
true

代码

import java.util.Scanner;

public class Main {
	int n,m,row1,row2,line1,line2;
	int k;//要判断的对数
	char[][]A;
	int []dx,dy;
	String[]result;
	public Main(){
		dx=new int[]{-1,1,0,0};//上下左右四个方向
		dy=new int[]{0,0,-1,1};
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		m=sc.nextInt();
		A=new char[n][m];
		
		for(int i=0;i<n;i++){
			String s=sc.next();
			for(int j=0;j<m;j++){
				A[i][j]=s.charAt(j);
			}
		}
		k=sc.nextInt();
		result=new String[k];
		for(int t=0;t<k;t++){
			row1=sc.nextInt()-1;//题目给出的数组下标是从1开始
			line1=sc.nextInt()-1;
			row2=sc.nextInt()-1;
			line2=sc.nextInt()-1;
			
			for(int i=row1;i<n;i++){
				for(int j=line1;j<m;j++)
					if(A[i][j]=='0')
						Search(i,j);
				result[t]=(A[row2][line2]=='2'?"true":"false");//走完看第二组数是否被标记,如果有被标记,说明此路可通
				break;
						
			}
			for(int i=0;i<n;i++){//refresh将数组重新变回原来的0 1
				for(int j=0;j<m;j++)
					if(A[i][j]=='2')
						A[i][j]='0';
			}
	}
		for(int i=0;i<k;i++){
			System.out.println(result[i]);
		}
}			
	void Search(int x,int y){//查找上下左右是否可走
		A[x][y]='2';
		for(int a=0;a<4;a++){
			int tx=x+dx[a],ty=y+dy[a];
			if(tx>=0 && tx<n && ty>=0 && ty<m &&A[tx][ty]=='0')//不越界,没有被标记,可以走
				Search(tx,ty);
		}
	}
	public static void main(String args[]){
		Main c=new Main();
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

callmeCassie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值