走迷宫、求最少步数
package bfs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import static java.lang.Integer.parseInt;
import static java.lang.System.in;
public class WalkTheMazeForTheMinimumNumberOfSteps {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
int num = parseInt(bf.readLine());
String[] strArr = new String[num];
for (int i = 0; i < num; i++) {
strArr[i] = bf.readLine();
}
bf.close();
int[][] map = new int[num][num];
for (int i = 0; i < num; i++) {
for (int i1 = 0; i1 < num; i1++) {
if (strArr[i].charAt(i1) == 'S') {
map[i][i1] = -1;
} else if (strArr[i].charAt(i1) == 'E') {
map[i][i1] = 2;
} else if (strArr[i].charAt(i1) == '#') {
map[i][i1] = 1;
} else {
map[i][i1] = 0;
}
}
}
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[i][j] == -1) {
System.out.println(getMinDistance(map, i, j));
}
}
}
}
public static int[] getLocation(int i, int j) {
int[] location = new int[2];
location[0] = i;
location[1] = j;
return location;
}
public static boolean isValidInMap(int i, int j, int[][] arr) {
return 0 <= i && i < arr.length && 0 <= j && j < arr[i].length;
}
public static int getMinDistance(int[][] map, int i, int j) {
int totalStep = 0;
boolean[][] visited = new boolean[map.length][map.length];
visited[i][j] = true;
Queue<int[]> queue = new LinkedList<>();
int[] location = getLocation(i, j);
queue.add(location);
int[][] nestStep = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!queue.isEmpty()) {
int queueSize = queue.size();
for (int i1 = 0; i1 < queueSize; i1++) {
int[] poll = queue.poll();
for (int[] ints : nestStep) {
int newX = poll[0] + ints[0];
int newY = poll[1] + ints[1];
if (isValidInMap(newX, newY, map) && map[newX][newY] == 2) {
return totalStep + 1;
}
if (isValidInMap(newX, newY, map) && !visited[newX][newY] && map[newX][newY] == 0) {
int[] newLocation = getLocation(newX, newY);
queue.add(newLocation);
visited[newX][newY] = true;
}
}
}
totalStep++;
}
return -1;
}
}