Data Structures and Algorithms7-10——Saving James Bond - Easy Version

我的Data Structures and Algorithms代码仓:https://github.com/617076674/Data-Structures-and-Algorithms

原题链接:https://pintia.cn/problem-sets/16/problems/672

题目描述:

知识点:图的深度优先遍历

思路:图的深度优先遍历

时间复杂度和空间复杂度均为O(N)。

由于中心点(0, 0)是一个圆形区域,假设从该区域能到达点的集合为first,我们的深度优先遍历就从该first集合为起点开始。

C++代码:

#include<iostream>
#include<cmath>
#include<vector>

using namespace std;

struct situation{
	int x, y;
	bool visited;
};

int N, D;
situation situations[100];
bool flag = false;

double calculateDistance(situation s1, situation s2);
bool canReach(situation s1, situation s2);	//从s1位置能否到达s2位置
bool canEscape(situation s);	//从s位置能否逃出
void dfs(situation &nowVisited); 

int main(){
	scanf("%d %d", &N, &D);
	for(int i = 0; i < N; i++){
		scanf("%d %d", &situations[i].x, &situations[i].y);
		situations[i].visited = false;
	}
	vector<situation> first;
	situation start;
	start.x = 0;
	start.y = 0;
	for(int i = 0; i < N; i++){
		if(calculateDistance(situations[i], start) <= D * 1.0 + 7.5){
			first.push_back(situations[i]);
		}
	}
	for(int i = 0; i < first.size(); i++){
		dfs(first[i]);
	}
	if(flag){
		printf("Yes\n");
	}else{
		printf("No\n");
	}
	return 0;
}

double calculateDistance(situation s1, situation s2){
	return sqrt(pow(s1.x - s2.x, 2) + pow(s1.y - s2.y, 2));
}

bool canReach(situation s1, situation s2){
	if(calculateDistance(s1, s2) <= D){
		return true;
	}else{
		return false;
	}
}

bool canEscape(situation s){
	int len1, len2;
	if(s.y >= 0){
		len1 = 50 - s.y;
	}else{
		len1 = s.y + 50;
	}
	if(s.x >= 0){
		len2 = 50 - s.x;
	}else{
		len2 = s.x + 50;
	}
	if(min(len1, len2) <= D){
		return true;
	}else{
		return false;
	}
} 

void dfs(situation &nowVisited){
	nowVisited.visited = true;
	if(canEscape(nowVisited)){
		flag = true;
		return;
	}
	for(int i = 0; i < N; i++){
		if(!situations[i].visited && canReach(nowVisited, situations[i])){
			dfs(situations[i]);
		}
	}
}

C++解题报告:

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值