0%

Acwing2060 奶牛选美(Flood Fill, DFS)

题目链接

思路

把两边的点分成两个集合, 求两个集合间距离最小即可
刚开始学java, 主要来练练手
注意对象数组实例化问题

1
2
3
LinkedList<Point>[] point = new LinkedList[2];
point[0] = new LinkedList<Point>();
point[1] = new LinkedList<Point>();

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Scanner;
import java.util.LinkedList;

class Point {
public int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

public class Main {
static int n, m;
static char[][] g = new char[55][55];
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
public static void dfs(int x, int y, LinkedList<Point> ps ) {
g[x][y] = '.';
ps.add( new Point(x, y) );
for(int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if(xx >= 0 && xx < n && yy >= 0 && yy < m && g[xx][yy] == 'X') {
dfs(xx, yy, ps);
}
}

}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList<Point>[] point = new LinkedList[2];
point[0] = new LinkedList<Point>();
point[1] = new LinkedList<Point>();
n = in.nextInt();
m = in.nextInt();
for(int i = 0; i < n; i++) {
String s = in.next();
g[i] = s.toCharArray();
}
for(int i = 0, k = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(g[i][j] == 'X') {
dfs(i, j, point[k++]);
}
}
}
int res = (int)1e8;
for(Point a : point[0]) {
for(Point b : point[1]) {
res = Math.min(res, Math.abs(a.x - b.x) + Math.abs(a.y - b.y) - 1);
}
}
System.out.println(res);

}
}

求大佬赏个饭