您的位置:首页 > 其它

迷宫最近距离

2018-02-27 14:40 113 查看




广搜代码如下:import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main
{
public static final int[][] maze = new int[][] {
{0,1,0,0,0,1,1,1,0,1,0,1},
{0,0,0,1,0,0,0,0,1,0,0,1},
{0,1,0,1,0,1,1,1,0,1,0,0},
{0,1,0,0,0,0,0,1,0,0,1,1},
{0,0,0,0,1,0,0,0,0,0,0,0},
{0,0,1,0,0,0,1,0,0,0,1,0},
{0,0,1,0,0,0,0,0,1,0,0,0},
{1,0,0,1,0,1,0,0,0,1,0,1},
{0,0,1,0,1,0,1,0,1,0,0,0},
{0,0,0,0,0,1,0,0,0,1,1,0},
{0,0,0,0,0,1,0,0,0,0,0,0},
{0,1,0,1,0,0,0,1,0,1,0,0}
};
public static final int N = 12;
public static int sx, sy, gx, gy;
public static int[] dx = new int[] {1, 0, -1, 0};
public static int[] dy = new int[] {0, 1, 0, -1};
public static int[][] d = new int[150][150];//记录到该点最小步数
public static final int INF = 10000000;
public static class Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
sx = cin.nextInt();
sy = cin.nextInt();
gx = cin.nextInt();
gy = cin.nextInt();
cin.close();
System.out.println(bfs());
}
public static int bfs()
{
Queue<Point> queue = new LinkedList<Point>();
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
d[i][j] = INF;//初始化
}
}
queue.add(new Point(sx, sy));
d[sx][sy] = 0;//到起点的步数为0
while (!queue.isEmpty())
{
Point p = queue.poll();
if (p.x == gx && p.y == gy) break;
for (int i = 0; i < 4; ++i)
{
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if (nx >= 0 && nx < N && ny >= 0 && ny < N && maze[nx][ny] != 1 && d[nx][ny] == INF)
{
queue.add(new Point(nx, ny));
d[nx][ny] = d[p.x][p.y] + 1;
}
}
}
//到达不了的情况
if (d[gx][gy] == INF)
{
return 10000;
}
return d[gx][gy];
}
}
=============================我是一个反应迟钝的程序员==============================
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: