这算是我第一次拿Java写算法,好多小细节要注意。
题目链接:Problem - 1241 (hdu.edu.cn)https://acm.hdu.edu.cn/showproblem.php?pid=1241
BFS的思想(我理解的)是:从图中的某一个点出发,找到与这个点相邻的所有的点,把它们加入队列中,然后取出队列中的第一个元素(删掉),继续找与它相邻的所有的点,把这些点依次加到队列末尾,直到队列为空的时候,BFS结束。
当然在实际写代码的过程中,除了队列,可能还需要一个数组(记录整个图),一个数组(记录是否访问过图中的该节点,访问该节点的顺序序号)等等。
下面的代码是借鉴别人的,在队列的选择上,使用了LinkedList,其中的节点用Node类表示,然后遍历过的是‘@’的节点,就改成‘*’,没有重新开一个数组,在我看来,这比重新用一个数组记录要好。
import java.util.LinkedList;
import java.util.Scanner;
public class Main{
int fx[] = {1, 1, 1, 0, 0, -1, -1, -1};
int fy[] = {1, 0, -1, -1, 1, 1, 0, -1};
LinkedList<Node> nodes = new LinkedList<>();
int m, n;
int total;//用来记录总的油田数
char[][] map;
public static void main(String[] args) {
new Main().solve();
}
private void solve() {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
total = 0;
m = in.nextInt();
n = in.nextInt();
if (m == 0 && n == 0) {
break;
}
map = new char[m][n];
for (int i = 0; i < m; i++) {
String s = in.next();
map[i] = s.toCharArray();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] == '@') {
total++;
Node node = new Node(i, j);
nodes.add(node);
BFS();
}
}
}
System.out.println(total);
}
}
private void BFS() {
//linkedHashSet不为空的时候
while (!nodes.isEmpty()) {
Node node = nodes.removeFirst();
//检查当前位置的八个方向是否也是'@'符号
for (int i = 0; i < 8; i++) {
int x = node.x + fx[i];
int y = node.y + fy[i];
if (check(x, y)) {
map[x][y] = '*';
nodes.add(new Node(x, y));
}
}
}
}
private boolean check(int x, int y) {
return x >= 0 && x <= m - 1 && y >= 0 && y <= n - 1 && map[x][y] == '@';
}
}
class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}