NOJ [1296] Between The Island

链接地址:http://ac.nbutoj.com/Problem/view.xhtml?id=1296

死月最爱讲故事了,这次他讲了个很恐怖的故事。
很久很久以前,有一片区域里有很多小岛,岛上住着很多幽灵。人类为了消灭幽灵,就开始造桥将两座岛连起来。只要所有岛都连起来了,不管是直接的还是间接的,这样一来就可以到达这座岛,并且跟幽灵战斗了。
那么这题该怎么做呢?
首先,这个区域是一个长方形,M*N的。
然后,'+'表示海的一部分,'0'表示岛的一部分。
那么至少要造几座桥才能把所有的岛连起来呢?
答案显而易见,桥的数量 = 岛的数量 - 1。
那么我们只要数出岛的数量,就可以知道桥的数量了。
题目描述里说到了,只要'0'是相邻的,就属于同一个岛。那么,我们只要DFS一下,就可以得到岛的数量了。

以下是我出题的代码。
#include <set>
#include <list>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

int m, n;
int map[60][60];
int dir[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};

void dfs(int a,int b)
{
int x, y;
for (int i = 0; i < 4; i++)
{
x = a + dir[i][0];
y = b + dir[i][1];
if (!map[x][y])
{
map[x][y] = 1;
dfs(x, y);
}
}
}

int main()
{
int s;

//freopen("B.in", "r", stdin);
//freopen("B.out", "w", stdout);

while (~scanf("%d%d", &m, &n))
{
getchar();
memset(map, -1, sizeof(map));
s = -1;
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (getchar() == '0') map[i][j] = 0;
}
getchar();
}
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (!map[i][j])
{
map[i][j] = 1;
dfs(i, j);
s++;
}
}
}
printf("%d\n", s);
}

return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值