牛客网 8.2 2017网易校招 Java 第二题 地牢逃脱

题目大致如下:

输入n,m,为地牢长和宽,下面输入n行m列的字符,如果为‘.’那么代表此处可以通行,否则无法通行,接下去,代表,地牢入口在哪,输入一行X,Y。代表入口地址,接下面是有几种走法,输入一个数字numb,下面每行有2个数字,代表如何行走。默认出口为右下角。求最坏情况下多少次能找到出口。

输入事例:

3 3 

. . .

. . .

. . .

0 1

4

0 1

  1 0

-1 0

0 -1

输出:

3


我用dfs搜索整个地牢,如果找到出口,就记录行走的步数,最后求所有解中的最大值即可。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class 地牢逃脱 {
	static ArrayList<Integer> ans = new ArrayList<Integer>();

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int m = sc.nextInt();
		// 1<=n,m<=50
		char[][] d = new char[n][m];
		boolean[][] is = new boolean[n][m];
		// 边界这儿在0<=n,m<=49
		// 初始化地牢
		for (int i = 0; i < n; i++) {
			String stdin = sc.next();
			for (int j = 0; j < m; j++) {
				d[i][j] = stdin.toCharArray()[j];
				is[i][j] = false;
			}
		}
		// 初始化其实位置
		int startx = sc.nextInt();
		int starty = sc.nextInt();

		// 方向次数
		int t = sc.nextInt();
		// 初始化上下左右,用数组方便遍历
		int[][] dir = new int[t][2];

		for (int i = 0; i < t; i++) {
			int x = sc.nextInt();
			int y = sc.nextInt();
			dir[i][0] = x;
			dir[i][1] = y;
		}

		dfs(d, dir, startx, starty, 0, is);
		try {
			Collections.sort(ans);
			System.out.println(ans.get(0));
		} catch (Exception e) {
			System.out.println(-1);
		}
	}

	public static void dfs(char[][] d,int[][] dir,int x,int y,int count,boolean[][] is){
		is[x][y] = true;
		if(x == d.length-1 && y == d[0].length-1 ){
			ans.add(count);
			return;
		}
		
		for (int i = 0; i < dir.length; i++) {
			if(x+dir[i][0] < d.length && x + dir[i][0] >= 0 &&  y + dir[i][1] < d[0].length
					&& y+dir[i][1] >= 0 && d[x+dir[i][0]][y+dir[i][1]] == '.' && is[x+dir[i][0]][y+dir[i][1]] == false)
			{
				dfs(d,dir,x+dir[i][0],y+dir[i][1],count+1,is);
			}
		}
		
		is[x][y] = false;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值