POJ 2386 lake counting
POJ 2386 lake counting
本题主要是运用dfs来计算lake的数目:
(Scanner没有nextChar()方法。第一次知道_)
import java.util.Scanner;
public class poj2386 {
static char[][] lake=new char[100][100];
static int n=0,m=0;
static int count=0;
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
n=s.nextInt();m=s.nextInt();
String str;
//input
for (int i = 0; i < n; i++) {
str=s.next();
for (int j = 0; j < m; j++) {
lake[i][j]=str.charAt(j);
}
}
//遍历
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (lake[i][j]=='W'){
dfs(i,j);
count++;
}
}
}
System.out.println(count);
}
//不断dfs直到所有的附件可接触的点,均更换为'.'
public static void dfs(int x,int y){
lake[x][y]='.';
for (int i = -1; i <=1 ; i++) {
for (int j = -1; j <= 1; j++) {
int nx = x + i, ny = y + j;
if (0 <= nx && nx < n && ny >= 0 && ny < m && lake[nx][ny] == 'W') {
dfs(nx, ny);
}
}
}
}
}

浙公网安备 33010602011771号