pat L3-008 DFS深度优先搜索
来源:互联网 发布:sql语句约束01 编辑:程序博客网 时间:2024/06/11 13:01
题目内容
题目内容见连接:https://www.patest.cn/contests/gplt/L3-008
题目分析
1.典型的图应用,并且是深度优先搜索
2.深度优先搜索,类似于树的层次遍历,需要用到队列。首先把对头元素入队,然后依然对于对头元素邻接的节点入队,再一个一个出队列。
3.技巧:利用链表形式,即vector< vector >,在进行入队处理的时候,一定要倒着入队,因为题目要求步数一致,按最小编号输出,所以是技巧啊!
题目代码
#include <iostream>#include <vector>#include <queue>/* run this program using the console pauser or add your own getch, system("pause") or input loop */using namespace std;const int NUM = 10000+5;vector< vector<int> > v(NUM);bool visited[NUM] = {false};int DFS(int n){ for(int i=0;i<NUM;i++){ visited[i]=false; } queue<int> q; q.push(n); visited[n]=true; int temp = -1; while(!q.empty()){ int top = q.front(); temp = top; //cout<<"top: "<<top<<endl; q.pop(); for(int i=v[top].size()-1;i>=0;i--){ if(visited[v[top][i]]==false){ q.push(v[top][i]); visited[v[top][i]] = true; //cout<<"v["<<top<<"] ["<<i<<"]: "<<v[top][i]<<endl; } } } return temp;} int main(int argc, char *argv[]) { int n,m,k; cin>>n>>m>>k; for(int i=0;i<m;i++){ int num1,num2; cin>>num1>>num2; v[num1].push_back(num2); v[num2].push_back(num1); } for(int i=0;i<k;i++){ int x; cin>>x; if(x==DFS(x)){ cout<<"0"<<endl; } else{ cout<<DFS(x)<<endl; } } return 0;}
阅读全文
0 0
- pat L3-008 DFS深度优先搜索
- 深度优先搜索 DFS
- 深度优先搜索 DFS
- DFS 深度优先搜索
- DFS 深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- DFS深度优先搜索
- 深度优先搜索(DFS)
- dfs深度优先搜索
- dfs 深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- DFS深度优先搜索
- 深度优先搜索(DFS)
- 深度优先搜索DFS
- 深度优先搜索(DFS)
- Java方法设置超时
- 【spark】编程代码,随笔记录
- JESD204B概述
- Android之极光推送发送自定义消息
- 漫谈递归:递归的思想
- pat L3-008 DFS深度优先搜索
- 提高代码阅读能力的7种方法
- 猫狗队列问题
- Jetpack 安装
- 欢迎使用CSDN-markdown编辑器
- CentOs7 搭建基于最新版 Redis 集群环境之图文详解
- 内部类----概述
- python+read()+、readline()和+readlines()的区别和用法
- python学习