9 6
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
45
BFS
java
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
//. 黑色
//# 红色
//@ 黑色开始
static final int N = 11;
static int n,m,ans = 1;
static char[][] g = new char[N][N];
static boolean[][] vis = new boolean[N][N];
public static void bfs(int[] start) {
Deque<int[]> dq = new LinkedList<>();
dq.addLast(start);
vis[start[0]][start[1]] = true;//@记录一次 ans初始值为1
int[] dx = new int[] {1,-1,0,0};
int[] dy = new int[] {0,0,1,-1};
while(!dq.isEmpty()) {
int[] t = dq.pollFirst();
for(int i=0;i<4;i++) {
int x = t[0]+dx[i];
int y = t[1]+dy[i];
if(x<0||x>n-1||y<0||y>m-1)
continue;
if(g[x][y] == '#')
continue;
if(vis[x][y])//如果访问过则continue
continue;
else {//没有访问过要标记为访问过之后 ans++ 然后入队列
vis[x][y] = true;
ans++;
dq.addLast(new int[] {x,y});
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
sc.nextLine();
g = new char[n][m];
for(int i=0;i<n;i++)
g[i] = sc.nextLine().toCharArray();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(g[i][j] == '@') {
bfs(new int[] {i,j});
System.out.println(ans);
return ;
}
}
}
}
}
DFS
java
import java.util.Scanner;
public class Main {
//. 黑色
//# 红色
//@ 黑色开始
static final int N = 11;
static int n,m,ans = 1;
static char[][] g = new char[N][N];
static boolean[][] vis = new boolean[N][N];
static int[] dx = new int[] {1,-1,0,0};
static int[] dy = new int[] {0,0,1,-1};
public static void dfs(int x1,int y1) {
for(int i=0;i<4;i++) {
int x2 = x1+dx[i];
int y2 = y1+dy[i];
if(x2<0||x2>n-1||y2<0||y2>m-1)
continue;
if(g[x2][y2] == '#')
continue;
if(vis[x2][y2])
continue;
else {
vis[x2][y2] = true;
ans++;
dfs(x2,y2);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
sc.nextLine();
g = new char[n][m];
for(int i=0;i<n;i++)
g[i] = sc.nextLine().toCharArray();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(g[i][j] == '@') {
vis[i][j] = true;//@标记一次 ans初始为1
dfs(i,j);
System.out.println(ans);
return ;
}
}
}
}
}