Problem - 1312 (hdu.edu.cn)https://acm.hdu.edu.cn/showproblem.php?pid=1312用一个队列存储节点,访问过的节点需要标记,最后注意一下cnt计数即可。
BFS的思想见:
import java.util.LinkedList;
import java.util.Scanner;
public class Main{
char[][] map;
int m, n, cnt, x, y;
int[] fx = {0, 0, 1, -1};
int[] fy = {1, -1, 0, 0};
LinkedList<Node> list;
public static void main(String[] args) {
new Main().solve();
}
public void solve() {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
n = in.nextInt();
m = in.nextInt();
if (n == 0 && m == 0) {
break;
}
cnt = 1;
map = new char[m][n];
list = new LinkedList<>();
for (int i = 0; i < m; i++) {
map[i] = in.next().toCharArray();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] == '@') {
x = i;
y = j;
break;
}
}
}
Node node = new Node(x, y);
list.add(node);
BFS();
System.out.println(cnt);
}
}
private void BFS() {
while (!list.isEmpty()) {
Node n = list.removeFirst();
for (int i = 0; i < 4; i++) {
int x_ = n.x + fx[i];
int y_ = n.y + fy[i];
if (check(x_, y_)) {
cnt++;
map[x_][y_] = '#';
list.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] != '#' && map[x][y] != '@';
}
}
class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}