思路:使用dfs找出两个相邻的斑点,搜索过的点改为'.'防止重复统计,然后依次遍历两个斑点内的点,找出最小曼哈顿距离。
import java.util.*;
public class Main {
static int n, m;
static char[][] g;
static List<int[]>[] points = new ArrayList[2];
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
private static void dfs(int a, int b, List<int[]> q) {
q.add(new int[]{a, b});
g[a][b] = '.';
for (int i = 0; i < 4; i++) {
int x = a + dx[i], y = b + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 'X') {
dfs(x, y, q);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
g = new char[n][m];
sc.nextLine();
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
g[i] = line.toCharArray();
}
int k = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == 'X') {
points[k] = new ArrayList<>();
dfs(i, j, points[k++]);
}
}
}
int res = 110;
for (int[] a : points[0]) {
for (int[] b : points[1]) {
res = Math.min(res, Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]));
}
}
System.out.println(res - 1);
}
}
标签:int,++,DFS,sc,points,static,选美,2060,new
From: https://www.cnblogs.com/he0707/p/18095657/lanqiaobei11