BFS解法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
private static int count = 1;
private static int[] dx = {-1, 0, 1, 0};
private static int[] dy = {0, 1, 0, -1};
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
//支持多组数据测试
while (true) {
String[] s1 = read.readLine().split(" ");
int n = Integer.parseInt(s1[0]);
int m = Integer.parseInt(s1[1]);
if (n == 0 && m == 0) break;
int startX = 0, startY = 0;
Character[][] chs = new Character[m][n];
for (int x = 0; x < chs.length; x++) {
char[] s = read.readLine().toCharArray();
for (int y = 0; y < chs[x].length; y++) {
if (s[y] == '@') {
startX = x;
startY = y;
}
chs[x][y] = s[y];
}
}
count = 1;
bfs(chs, startX, startY);
System.out.println(count);
}
}
public static void bfs(Character[][] chs, int startX, int startY) {
chs[startX][startY] = '!';
//存放符合条件的结果
Queue queue = new LinkedList<>();
queue.offer(new int[]{startX, startY});
while (!queue.isEmpty()) {
int[] poll = queue.poll();
int x = poll[0], y = poll[1];
for (int i = 0; i < 4; i++) {
x = x + dx[i];
y = y + dy[i];
if (x >= 0 && x < chs.length && y >= 0 && y < chs[0].length && chs[x][y] == '.') {
queue.offer(new int[]{x, y});
chs[x][y] = '!';
count++;
}
//恢复坐标
x = x - dx[i];
y = y - dy[i];
}
}
}
}
DFS解法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
private static int count = 0;
private static int[] dx = {-1, 0, 1, 0};
private static int[] dy = {0, 1, 0, -1};
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
//支持多组数据测试
while (true) {
String[] s1 = read.readLine().split(" ");
int n = Integer.parseInt(s1[0]);
int m = Integer.parseInt(s1[1]);
if (n == 0 && m == 0) break;
int startX = 0, startY = 0;
Character[][] chs = new Character[m][n];
for (int x = 0; x < chs.length; x++) {
char[] s = read.readLine().toCharArray();
for (int y = 0; y < chs[x].length; y++) {
if (s[y] == '@') {
startX = x;
startY = y;
}
chs[x][y] = s[y];
}
}
count = 0;
chs[startX][startY] = '.';
dfs(chs, startX, startY);
System.out.println(count);
}
}
public static void dfs(Character[][] chs, int startX, int startY) {
if (startX >= 0 && startX < chs.length && startY >= 0 && startY < chs[0].length && chs[startX][startY] == '.') {
count++;
chs[startX][startY] = '!';
for (int i = 0; i < 4; i++) dfs(chs, startX + dx[i], startY + dy[i]);
}
}
}