题目链接:https://cn.vjudge.net/problem/POJ-2386
题意:计算有多少个W的联通块
题解:学了一天java,写的第一个稍微复杂一点的程序,虽说不难。读nextLine时,要注意之前的回车清空,如果直接next,就不需要了
- nextLine()是以回车作为分割符进行读取 也就是说会从控制台接收控制台输入的一行数据,读入语句包含空格
- next() 是以空格和回车作为分割符进行读取的,如果一行输入包含空格,会按空格截断,只显示第一个空格之前的内容
import java.util.Scanner;
public class Main {
public static int[][] nex = {{1, 0}, {1, 1}, {1, -1}, {-1, 0}, {-1, 1}, {-1, -1}, {0, 1}, {0, -1}};
public static int n, m;
public static char [][] mp ;
public static void init() {
mp = new char[n][m];
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while(cin.hasNextInt()) {
n = cin.nextInt();
m = cin.nextInt();
init();
String str;
for(int i = 0; i < n; i++) {
str = cin.next();
mp[i] = str.toCharArray();
}
int ans = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(mp[i][j]=='W') {
dfs(i, j);
ans++;
}
}
}
System.out.println(ans);
}
}
public static void dfs(int x, int y) {
mp[x][y] = '.';
int x_, y_;
// System.out.println(x + " " + y);
for(int i = 0; i < 8; i++) {
x_ = x + nex[i][0];
y_ = y + nex[i][1];
if(judge(x_, y_))
dfs(x_, y_);
}
}
public static boolean judge(int x, int y) {
if(x < 0 || x >= n || y < 0 || y >= m ) return false;
if(mp[x][y] == '.') return false;
return true;
}
}