踏青

习题:踏青
蒜头君和他的朋友周末相约去召唤师峡谷踏青。他们发现召唤师峡谷的地图是由一块一块格子组成的,有的格子上是草丛,有的是空地。
草丛通过上下左右4个方向扩展其他草丛形成一片草地,任何一片草地中的格子都是草丛,并且所有格子之间都能通过上下左右连通。
如果用'#'代表草丛,'.'代表空地,下面的峡谷中有2片草地。
##..
..##
处在同一个草地的2个人可以相互看到,空地看不到草地里面的人。他们发现有一个朋友不见了,现在需要分头去找,
每个人负责一片草地,蒜头君想知道他们至少需要多少人。
输入格式
第一行输入n,m (1≤n,m≤100) 表示峡谷大小
接下来输入n行字符串表示峡谷的地形
输入格式
输出至少需要多少人
样例输入
5 6
.#....
..#...
..#..#
...##.
.#....
样例输出
5

代码如下:

import java.util.Scanner;
/*
5 6
.#....
..#...
..#..#
...##.
.#....
 * */
public class L3 {

	public static int n, m;
	public static char[][] map = new char[105][105];
	public static boolean[][] vis = new boolean[105][105];

	public static void dfs(int x, int y) {
		if (x < 0 || x >= n || y < 0 || y >= m || vis[x][y] || map[x][y] == '.')
			return;
		vis[x][y]=true;
		dfs(x-1,y);
		dfs(x+1,y);
		dfs(x,y-1);
		dfs(x,y+1);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		n = 5;//sc.nextInt();
		m = 6;//sc.nextInt();
		int cnt = 0;
		map[0]=".#....".toCharArray();
		map[1]="..#...".toCharArray();
		map[2]="..#..#".toCharArray();
		map[3]="...##.".toCharArray();
		map[4]=".#....".toCharArray();
//		for (int i = 0; i < n; i++) {
//			map[i] = sc.nextLine().toCharArray();
//			System.out.println();
//		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (!vis[i][j] && map[i][j] == '#') {
					dfs(i, j);
					cnt++;
				}
			}
		}
		System.out.println(cnt);

	}

}

猜你喜欢

转载自blog.csdn.net/qq_41921315/article/details/87931984