改进版笔试题迷宫问题--深度优先搜索

在迷宫上下左右移动的基础上,增加了飞行到中心对称位置处的限制

package com.alibaba.test;

import java.util.Scanner;

public class Main {
	static int[][] map;
	static int[][] vis;
	static int[][] move = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
	static Node[] q;
	static int m;
	static int n;
	static int beginx;
	static int beginy;
	static int endx;
	static int endy;
	static int feixingnum = 4;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		m = sc.nextInt();
		n = sc.nextInt();
		q = new Node[m * n];
		char[][] migong = new char[m][n];
		sc.nextLine();
		for (int i = 0; i < m; i++) {
			migong[i] = sc.nextLine().toCharArray();
		}
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (migong[i][j] == 'S') {
					beginx = i;
					beginy = j;
				}
				if (migong[i][j] == 'E') {
					endx = i;
					endy = j;
				}
			}
		}
		map = new int[m][n];
		vis = new int[m][n];
		System.out.println(bfs());
		sc.close();
	}

	public static int bfs() {
		int head = 0;
		int tail = 0;
		q[tail] = new Node(beginx, beginy, -1);
		vis[beginx][beginy] = 1;
		tail++;

		while (head < tail) {
			boolean flag = false;// 找没找到终点
			for (int i = 0; i < 5; i++) {
				if (i < 4) {
					int nx = q[head].x + move[i][0];
					int ny = q[head].y + move[i][1];
					if (check(nx, ny)) {
						vis[nx][ny] = 1;
						q[tail] = new Node(nx, ny, head);
						tail++;
					}
					if (nx == endx && ny == endy) {
						flag = true;
						break;
					}
				}
				if (i == 4 && feixingnum > 0) {
					int nx = m + 1 - q[head].x;
					int ny = n + 1 - q[head].y;
					if (check(nx, ny)) {
						vis[nx][ny] = 1;
						q[tail] = new Node(nx, ny, head);
						tail++;
						feixingnum--;
					}
					if (nx == endx && ny == endy) {
						flag = true;
						break;
					}
				}

			}
			head++;
			if (flag) {
				return tail-head;
			}

		}
		return -1;
	}

	static boolean check(int x, int y) {
		return x >= 0 && x < m && y >= 0 && y < n && vis[x][y] != 1 && map[x][y] != 1;
	}

}

class Node {
	int x, y, pre;

	Node() {
	}

	Node(int x, int y, int pre) {
		this.x = x;
		this.y = y;
		this.pre = pre;
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值