题意很简单,就是算合法的联通块个数,并且输出
但是因为粗心,做了很久,被自己蠢哭555
放代码 上去丢人
import java.util.*;
public class Main {
private static int r, c, sum = 0;
private static int dirc[][] = { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } };
private static char map[][] = new char[1010][1010];
private static boolean vis[][] = new boolean[1010][1010];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
r = scan.nextInt();
c = scan.nextInt();
String s;
for (int i = 1; i <= r; i++) {
s = scan.next();
for (int j = 0; j < c; j++) {
map[i][j + 1] = s.charAt(j);
}
}
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
if (Check(i, j)) {
System.out.println("Bad placement.");
return;
}
}
}
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
if (map[i][j] == '#' && vis[i][j] == false) {
BFS(i, j);
sum++;
}
}
}
System.out.println("There are " + sum + " ships.");
}
//判断#是否合法
public static boolean Check(int x, int y) {
int c = 0;
if (map[x][y] == '#')
c++;
if (map[x + 1][y] == '#')
c++;
if (map[x][y + 1] == '#')
c++;
if (map[x + 1][y + 1] == '#')
c++;
return c == 3;
}
// 计算每一个联通块的个数
public static void BFS(int x, int y) {
Queue<int[]> q = new LinkedList<int[]>();
q.offer(new int[] { x, y });
vis[x][y] = true;
while (!q.isEmpty()) {
int cur[] = q.poll();
// 注意啊,cur准备好了别忘了填
for (int i = 0; i < 4; i++) {
int dx = cur[0] + dirc[i][0];
int dy = cur[1] + dirc[i][1];
if (dx < 1 || dx > r || dy < 1 || dy > c || vis[dx][dy] || map[dx][dy] == '.') {
continue;
}
if (map[dx][dy] == '#' && !vis[dx][dy]) {
q.offer(new int[] { dx, dy });
vis[dx][dy] = true;
}
}
}
}
// 计算每一个联通块的个数
public static void DFS(int x, int y) {
vis[x][y] = true;
for (int i = 0; i < 4; i++) {
int dx = x + dirc[i][0];
int dy = y + dirc[i][1];
if (dx >= 1 && dx <= r && dy >= 1 && dy <= c && map[dx][dy] == '#' && vis[dx][dy] == false) {
DFS(dx, dy);
}
}
}
}