SDUT 2139 图结构练习——BFS——从起始点到目标点的最短步数
2016-07-25 11:28
323 查看
点击打开题目链接
#include <bits/stdc++.h>
using namespace std;
int n, m;
bool vis[1010];
int Graph[1010][1010];
void BFS();
struct node
{
int _end;
int step;
};
int main()
{
int u, v;
while(cin >> n >> m)
{
memset(Graph, 0, sizeof(Graph));
memset(vis, 0, sizeof(vis));
for(int i = 0; i < m; i++)
{
cin >> u >> v;
Graph[u][v] = 1;
}
BFS();
}
return 0;
}
void BFS()
{
queue<node *>Q;
node *tmp = new node;
tmp -> _end = n;
tmp -> step = 0;
Q.push(tmp);
vis
= 1;
while(!Q.empty())
{
node *now = Q.front();
Q.pop();
if(now -> _end == 1)
{
cout << now -> step << endl;
return;
}
for(int i = n; i >= 1; i--)
{
if(!vis[i] && Graph[now -> _end][i])
{
vis[i] = 1;
node *tmp = new node;
tmp->_end = i;
tmp->step = now->step+1;
Q.push(tmp);
}
}
}
cout << "NO" << endl;
}
#include <bits/stdc++.h>
using namespace std;
int n, m;
bool vis[1010];
int Graph[1010][1010];
void BFS();
struct node
{
int _end;
int step;
};
int main()
{
int u, v;
while(cin >> n >> m)
{
memset(Graph, 0, sizeof(Graph));
memset(vis, 0, sizeof(vis));
for(int i = 0; i < m; i++)
{
cin >> u >> v;
Graph[u][v] = 1;
}
BFS();
}
return 0;
}
void BFS()
{
queue<node *>Q;
node *tmp = new node;
tmp -> _end = n;
tmp -> step = 0;
Q.push(tmp);
vis
= 1;
while(!Q.empty())
{
node *now = Q.front();
Q.pop();
if(now -> _end == 1)
{
cout << now -> step << endl;
return;
}
for(int i = n; i >= 1; i--)
{
if(!vis[i] && Graph[now -> _end][i])
{
vis[i] = 1;
node *tmp = new node;
tmp->_end = i;
tmp->step = now->step+1;
Q.push(tmp);
}
}
}
cout << "NO" << endl;
}
相关文章推荐
- js算法: 图的两种表示方法以及广度优先算法
- 【日常练习 搜索】诡异的楼梯(队列+bfs)
- Surrounded Regions
- Word Ladder, Gray Code
- UVA 11624
- HDU1495
- HDU2612 Find a way
- HDU1241 Oil Deposits
- Hdu2444二分图
- http://codeforces.com/gym/100803/attachments A题 Bit String Reordering
- 最少步数BFS
- 转v_JULY_v的 BFS和DFS优先搜索算法
- 2015 寒假搜索专题 I - Meteor Shower(BFS)
- Same Tree
- E - Roads in the North
- DFS&BFS算法总结(1)
- Word Ladder I
- 图的BFS和DFS学习笔记
- [LeetCode] Binary Tree Level Order Traversal
- [LeetCode] Binary Tree Level Order Traversal II