题目出处点这里
思路:BFS。按顺序逐个对矩阵非零元素且未访问过的元素进行广搜,每一次广搜将此次可以走到的元素标记为已访问,最后记录bfs次数的就是细胞数。
代码如下:
package search;
import java.awt.Point;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class P1451 {
static int n, m, sum;
static char[][] arr;
static boolean[][] vis;
static int[] xx = { 0, 0, 1, -1 };
static int[] yy = { 1, -1, 0, 0 };
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
arr = new char[n][m];
vis = new boolean[n][m];
for (int i = 0; i < n; i++) {
String str = sc.next();
arr[i] = str.toCharArray();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!vis[i][j] && arr[i][j] != '0') {
bfs(i, j);
sum++;
}
}
}
System.out.println(sum);
}
public static void bfs(int x, int y) {
Queue<Point> q = new LinkedList<Point>();
q.add(new Point(x, y));
vis[x][y] = true;// 设为已访问过
while (!q.isEmpty()) {
Point p = q.poll();
for (int i = 0; i < 4; i++) {
int row = p.x + xx[i];
int col = p.y + yy[i];
if (row >= 0 && row < n && col >= 0 && col < m && !vis[row][col] && arr[row][col] != '0') {
q.add(new Point(row, col));
vis[row][col] = true;
}
}
}
}
}