题目
题目链接:2019. 拖拉机 - AcWing题库
干了一整天的活,农夫约翰完全忘记了他把拖拉机落在田地中央了。
他的奶牛非常调皮,决定对约翰来场恶作剧。
她们在田地的不同地方放了 N 捆干草,这样一来,约翰想要开走拖拉机就必须先移除一些干草捆。
拖拉机的位置以及 N 捆干草的位置都是二维平面上的整数坐标点。
拖拉机的初始位置上没有干草捆。
当约翰驾驶拖拉机时,他只能沿平行于坐标轴的方向(北,南,东和西)移动拖拉机,并且拖拉机必须每次移动整数距离。
例如,驾驶拖拉机先向北移动 2 单位长度,然后向东移动 3 单位长度。
拖拉机无法移动到干草捆占据的位置。
请帮助约翰确定他需要移除的干草捆的最小数量,以便他能够将拖拉机开到二维平面的原点。
代码
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
class node implements Comparable<node>
{
int x, y, dist;
public node(int x, int y, int dist) {
this.x = x;
this.y = y;
this.dist = dist;
}
@Override
public int compareTo(node o) {
return this.dist - o.dist;
}
}
public class Main {
static int n, sx, sy;
static int[][] dis = new int[2010][2010];
static boolean[][] f = new boolean[2010][2010];
static boolean[][] g = new boolean[2010][2010];
static int[] xx = {0, 0, 1, -1};
static int[] yy = {1, -1, 0, 0};
public static int dijkstra(node root)
{
Queue<node> q = new PriorityQueue<node>();
q.add(root);
while(!q.isEmpty())
{
node top = q.poll();
if(top.x == 0 && top.y == 0)
break;
if(f[top.x][top.y])
continue;
f[top.x][top.y] = true;
for(int i = 0; i < 4; i ++)
{
int tx = top.x + xx[i];
int ty = top.y + yy[i];
if(0 <= tx && tx < 2000 && 0 <= ty && ty < 2000)
{
int w = 0;
if(g[tx][ty])
w = 1;
if(top.dist + w < dis[tx][ty])
{
dis[tx][ty] = top.dist + w;
if(!f[tx][ty])
q.add(new node(tx, ty, dis[tx][ty]));
}
}
}
}
return dis[0][0];
}
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
for(int i = 0; i < dis.length; i ++)
Arrays.fill(dis[i], Integer.MAX_VALUE);
n = inScanner.nextInt();
sx = inScanner.nextInt();
sy = inScanner.nextInt();
dis[sx][sy] = 0;
for(int i = 1; i <= n; i ++)
{
int a, b;
a = inScanner.nextInt();
b = inScanner.nextInt();
g[a][b] = true;
}
inScanner.close();
int ans = dijkstra(new node(sx, sy, 0));
System.out.println(ans);
}
}
/*
7 6 3
6 2
5 2
4 3
2 1
7 3
5 4
6 4
*/