AcWing 1097. 池塘计数 java
原题链接
简单
池塘计数java版本
采用dfs会出现
java.lang.StackOverflowError错误
import java.io.*;
public class Main{
static BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
static char[][] arr;
static int n, m;
public static void main(String[] args) throws IOException{
String[] s = cin.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
arr = new char[n][m];
for (int i = 0; i < n; i++) {
String str = cin.readLine();
for (int j = 0; j < m; j++) {
arr[i][j] = str.charAt(j);
}
}
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++){
if (arr[i][j] == 'W') {
dfs(i, j);
res++;
}
}
}
System.out.println(res);
}
private static void dfs(int x, int y) {
arr[x][y] = '.';
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int a = x + i, b = y + j;
if (a >= 0 && a < n && b >= 0 && b < m && arr[a][b] == 'W') dfs(a, b);
}
}
}
}
采用宽搜使用队列实现 耗时1569 ms
import java.io.*;
import java.util.*;
public class Main{
static BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
static char[][] arr;
static int n, m;
static class Place {
int x;
int y;
Place(int i, int j) {
x = i;
y = j;
}
}
private static void bfs(int x, int y) {
Queue<Place> q = new LinkedList<>();
q.offer(new Place(x, y));
arr[x][y] = '.';
while (!q.isEmpty()) {
Place pl = q.poll();
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int a = pl.x + i, b = pl.y + j;
if (a >= 0 && a < n && b >= 0 && b < m && arr[a][b] == 'W') {
q.offer(new Place(a, b));
arr[a][b] = '.';
}
}
}
}
}
public static void main(String[] args) throws IOException{
String[] s = cin.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
arr = new char[n][m];
for (int i = 0; i < n; i++) {
String str = cin.readLine();
for (int j = 0; j < m; j++) {
arr[i][j] = str.charAt(j);
}
}
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++){
if (arr[i][j] == 'W') {
bfs(i, j);
res++;
}
}
}
System.out.println(res);
}
}
DFS剪枝