import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static int n, m; // 记录地图 public static char[][] chars = new char[110][110]; // 记录已访问 public static boolean[][] vis = new boolean[110][110]; // 记录答案 public static int ans = 0; // x,y 八个位置分别对应上下左右以及四个对角线方向 public static int[] dx = {0,0,1,-1,-1,1,-1,1}; public static int[] dy = {1,-1,0,0,1,1,-1,-1}; public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); String sa = in.nextLine(); String[] strs = new String[n]; int index = 0; char[][] cs = new char[n][m]; // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case strs[index] = in.nextLine(); cs[index] = strs[index].toCharArray(); index++; } for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ chars[i][j] = cs[i - 1][j - 1]; } } // 遍历整个地图,统计水坑数量 for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ if(chars[i][j] == 'W' && !vis[i][j]){ ans++; // 发现一个新水坑 dfs(i, j); // 遍历该水坑的所有格子 } } } System.out.println(ans); } // W是水,'.'是干地 // 这里的dfs是遍历当前水坑的所有位置,一次标记一个水坑的所有位置 public static void dfs(int x, int y){ vis[x][y] = true; // 按照上下左右四个对角线的顺序执行 for(int i = 0; i < 8; i++){ int nx = x + dx[i]; int ny = y + dy[i]; // 检查边界 if(nx < 1 || nx > n || ny < 1 || ny > m){ continue; } // 判断是否为未访问的水坑 if(!vis[nx][ny] && chars[nx][ny] == 'W'){ dfs(nx,ny); } } } }