在迷宫上下左右移动的基础上,增加了飞行到中心对称位置处的限制
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;
}
}