hdu 1307(dfs+map+set)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1307

先说一下题意,就是给你n维起始点和终点的坐标,然后后面给出一系列的点,每一行表示这两个点之间有通路,最后让你判断一下能否从起点出发走到终点。

由于最多不超过10维,那么我们把每个点的坐标转化为一个整数,然后建邻接表,这样dfs就可以了(值得注意的是我们用set来判重,当然你也可以用数组什么的)

可以说是dfs+map+set的妙用了!

#include <iostream>
#include <map>
#include <set>
#include <vector>
using namespace std;

map <int, vector <int> > Map;
set <int> used;

bool read(int &num, int n)
{
	int i, t;
	num = 0;
	for (i=0;i<n;++i)
	{
		scanf("%d", &t);
		if (t==-1) return false;
		num = num * 10 + t;
	}
	return true;
}

bool dfs(int s, int e)
{
	vector<int>::iterator it = Map[s].begin();
	for (;it!=Map[s].end();++it)
	{
		if (*it == e) return true;
		if (!used.count(*it))
		{
			used.insert(*it);
			if (dfs(*it, e)) return true;
		}
	}
	return false;
}

int main()
{
	int n, c, s, e, f, t;
	for (c=1;scanf("%d",&n),n;++c)
	{
		Map.clear();
		read(s, n);
		read(e, n);
		while (read(f, n))
		{
			read(t, n);
			Map[f].push_back(t);
			Map[t].push_back(f);
		}
		used.clear();
		if (dfs(s, e))
		printf("Maze #%d can be travelled\n", c);
		else
		printf("Maze #%d cannot be travelled\n", c);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值