POJ - 2386 Lake Counting dfs搜索

题目链接: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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值