您的位置:首页 > 理论基础 > 数据结构算法

数据结构 && 实验7 && 图的操作

2013-11-25 09:12 302 查看
一、实验目的及要求

1理解图的抽象数据类型的定义,及在C语言环境中的表示方法。

2理解图的基本操作的算法,及在C语言环境中一些主要基本操作的实现。

3在C语言环境下实现图的应用操作:

①使用邻接矩阵存储结构,实现无向网的创建和输出。

②利用基本操作集,实现采用邻接表表示的无向图的非递归的广度优先遍历算法。
二、实验内容
经过对实验目的及要求的分析,本实验实现了基于邻接矩阵存储的无向网的创建、基于邻接表存储的无向图的广度优先遍历算法的编码。

三、代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxnode = 1000;
struct m_node
{
int maps[maxnode][maxnode];
int n, m;
void init()
{
memset(maps,-1,sizeof maps);
n = m = 0;
}

void create()
{
scanf("%d%d",&n, &m);
for(int i = 0 ; i <= n ; ++ i) maps[i][i]=0;
for(int i = 0 ; i < m ; ++ i)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
maps[b][a] = maps[a][b] = c;
}
}

void print()
{
for(int i = 1 ; i <= n ; ++ i)
{
for(int j = 1 ; j <= n ; ++ j)
{
printf("%5d", maps[i][j]);
}
printf("\n");
}
}
}m;

struct Edge
{
int from, to;
double dist;
Edge(int from, int to, double dist):from(from),to(to),dist(dist) {}
};

struct HeapNode
{
double d;
int u;
HeapNode(double d, int u):d(d),u(u) {}
bool operator<(const HeapNode& rhs) const { return d>rhs.d;}
};

struct BFS
{
int n, m;
vector<Edge> edges;
vector<int> G[maxnode];
bool done[maxnode];

void init(int n)
{
this->n = n;
for(int i = 0 ; i < n ; ++ i) G[i].clear();
edges.clear();
}

void AddEdge(int from, int to, double dist)
{
edges.push_back(Edge(from,to,dist));
m = edges.size();
G[from].push_back(m-1);
}

void bfs(int s)
{
queue<HeapNode> Q;
memset(done, 0, sizeof done);
Q.push(HeapNode(1.0,s));
while(!Q.empty())
{
HeapNode x = Q.front(); Q.pop();
int u = x.u;
if(done[u]) continue;
done[u] = true;
for(int i = 0 ; i < (int)G[u].size() ; ++ i)
{
Edge& e = edges[G[u][i]];
Q.push(HeapNode(1.0, e.to));
}
}
}
}bfs;
int main()
{
freopen("in","r",stdin);
m.init();
m.create();
m.print();

int ns, ms;
scanf("%d%d", &ns, &ms);
bfs.init(ns);
for(int i = 0 ; i < ms ; ++ i)
{
int a, b;double c;
scanf("%d%d%lf",& a,&b,&c);
bfs.AddEdge(a, b, c);
}
bfs.bfs(1);
return 0;
}

四、实验心得
  1、把边存入临接矩阵,再输出矩阵,这是让我们练习输入输出么。。。

  2、非递归的广度优先搜索。。。  谁见过递归版本的广度优先搜索,发给我一份,谢谢!

  3、只要实现BFS,连个功能都不用实现,copy了dij的模板修改成了bfs,很方便!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构