简单的广度优先

题目链接:幽灵船
注意判断起点就是终点的情况。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class source
{
public static void main(String[] args) throws Exception
{
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());

final int W = Integer.parseInt(st.nextToken());
final int H = Integer.parseInt(st.nextToken());

final String[][] graph = new String[H][W];
final int[][] isSearched = new int[H][W];
String[] tag;
int[] startPoint = new int[2];
int[] endPoint = new int[2];
for (int i = 0; i < H; i++)
{
st = new StringTokenizer(br.readLine());
tag = st.nextToken().split("");
for (int j = 0; j < W; j++)
{
graph[i][j] = tag[j];
isSearched[i][j] = -1;
if (tag[j].equals("X"))
{
isSearched[i][j] = -2;
} else if (tag[j].equals("S"))
{
startPoint = new int[]
{ i, j };
isSearched[i][j] = 0;
} else if (tag[j].equals("E"))
{
endPoint = new int[]
{ i, j };
}
}
}

final int[] finalStartPoint = startPoint;
final Queue<int[]> queue = new LinkedList<int[]>();
queue.offer(finalStartPoint);
if (graph[finalStartPoint[0]][finalStartPoint[1]].equals("E"))
{
System.out.println(0);
return;
}
boolean findPosition = false;
int[] currentPoint;
while (queue.size() != 0)
{
currentPoint = queue.poll();
int x, y;
x = currentPoint[0];
y = currentPoint[1];
// under
if (x - 1 >= 0 && isSearched[x - 1][y] == -1)
{
isSearched[x - 1][y] = isSearched[x][y] + 1;
if (graph[x - 1][y].equals("E"))
{
findPosition = true;
break;
}
queue.offer(new int[]
{ x - 1, y });
}
// above
if (x + 1 < H && isSearched[x + 1][y] == -1) { isSearched[x + 1][y] = isSearched[x][y] + 1; if (graph[x + 1][y].equals("E")) { findPosition = true; break; } queue.offer(new int[] { x + 1, y }); } // left if (y - 1 >= 0 && isSearched[x][y - 1] == -1)
{
isSearched[x][y - 1] = isSearched[x][y] + 1;
if (graph[x][y - 1].equals("E"))
{
findPosition = true;
break;
}
queue.offer(new int[]
{ x, y - 1 });
}
// right
if (y + 1 < W && isSearched[x][y + 1] == -1)
{
isSearched[x][y + 1] = isSearched[x][y] + 1;
if (graph[x][y + 1].equals("E"))
{
findPosition = true;
break;
}
queue.offer(new int[]
{ x, y + 1 });
}
}
if (findPosition)
{
System.out.println(isSearched[endPoint[0]][endPoint[1]]);
} else
{
System.out.println(-1);
}
}
}

posted @ 2021-04-30 15:45  Monstro  阅读(55)  评论(0)    收藏  举报