您的位置:首页 > 其它

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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BFS