算法题-分治法解决the number of islands

题目:

Given a 2d m * n grid map of ’1’s (land) and ’0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

INPUT:

Line 1: m and n.

Line 2: ’1’ or ’0’ in grid and split by spaces

OUTPUT:

Line 1: number of islands.


代码:

#include<iostream>
#include<vector>

using namespace std;

void affect(vector<vector<int>>& v,int i,int j) {
	
	if ( i >= v.size() || j >= v[0].size() || i < 0 || j < 0|| v[i][j] == 0)return;
	v[i][j] = 0;

	affect(v, i + 1, j);
	affect(v, i - 1, j);
	affect(v, i, j + 1);
	affect(v, i, j - 1);

}

int main() {

	int m,n;
	cin >>m>> n;
	vector<vector<int>> v(m, vector<int>(n, 0));
	
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			cin >> v[i][j];
		}
	}
	//v = { {1,1,1,1,0},{1,1,0,1,0},{1,1,0,0,0},{0,0,0,0,0} };
	int count = 0;

	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			if (v[i][j] == 1) {
				count++;
				affect(v, i, j);
			}
		}
	}
	
	cout << count;

	int c;
	cin >> c;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值