邻接矩阵存储结构
保存图的顶点名称,需要一个一维数组;保存顶点间的关系,需要一个二维数组;保存图的类型(有向图、无向图等)需要一个整形存储;另外,还需要明确图的顶点数与边数,方便创建等操作。
代码
#include<iostream>
#include<cstring>
#include<queue>
#define INFINITY 0
using namespace std;
const int MAX_SIZE = 128;
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
typedef struct {
char vexname[MAX_SIZE];
int arcs[MAX_SIZE][MAX_SIZE];
int kind; // 0 1 2 3
int vexnum, arcnum; // 点数、边数
}Graph;
typedef struct{
int x, y;
}node;
void GraphInit(Graph &G)
{
memset(G.arcs, 0, sizeof(G.arcs));
G.kind = G.vexnum = G.arcnum = 0;
}
int FindIndexOf(Graph G, char name)
{
for (int i = 0;i < G.vexnum;i++)
if (name == G.vexname[i]) return i;
return -1;
}
void CreateGraph(Graph &G)
{
cout << "输入点数与边数:" << endl;
cin >> G.vexnum >> G.arcnum;
cout << "输入图的类型:" << endl;
cin >> G.kind;
cout << "输入顶点名称:" << endl;
for (int i = 0;i < G.vexnum;i++) cin >> G.vexname[i];
for (int i = 0;i < G.vexnum;i++)
for (int j = 0;j < G.vexnum;j++) G.arcs[i][j] = INFINITY;
cout << "输入边的位置与权重:" << endl;
for (int i = 0;i < G.arcnum;i++)
{
char n1, n2;
int weight;
cin >> n1 >> n2 >> weight;
int t1 = FindIndexOf(G, n1), t2 = FindIndexOf(G, n2);
if (t1 == -1 || t2 == -1)
exit(0);
G.arcs[t1][t2] = weight;
G.arcs[t2][t1] = weight;
}
}
void OutputGraph(Graph G)
{
for (int i = 0;i < G.vexnum;i++) cout << G.vexname[i];
cout << endl;
for (int i = 0;i < G.vexnum;i++)
{
for (int j = 0;j < G.vexnum;j++)
printf("%4d", G.arcs[i][j]);
cout << endl;
}
}
int vis[MAX_SIZE][MAX_SIZE] = {0};
void GraphDFS(Graph G, int x, int y)
{
if(x==G.vexnum && y==G.vexnum)
{
cout<<endl;
return;
}
for(int i = 0;i < 4;i++)
{
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(!vis[tx][ty] && tx>=0 && ty>=0 && tx<G.vexnum && ty<G.vexnum)
{
vis[tx][ty] = 1;
cout<<G.arcs[tx][ty];
GraphDFS(G, tx, ty);
vis[tx][ty] = 0;
}
}
}
void GraphBFS(Graph G)
{
int vis[MAX_SIZE][MAX_SIZE];
queue<node> q;
node t;
t.x = 0;t.y = 0;
q.push(t);
while(!q.empty())
{
node p = q.front();
cout<<G.arcs[p.x][p.y]<<' ';
q.pop();
for(int i = 0;i < 4;i++)
{
int tx = p.x + dir[i][0];
int ty = p.y + dir[i][1];
if(!vis[tx][ty] && tx>=0 && ty>=0 && tx<G.vexnum && ty<G.vexnum)
{
vis[tx][ty] = 1;
node n;
n.x = tx;
n.y = ty;
q.push(n);
}
}
}
}
int main()
{
Graph G;
GraphInit(G);
CreateGraph(G);
OutputGraph(G);
// cout<<"DFS result:"<<endl;
// GraphDFS(G, 0, 0);
cout<<"BFS result:"<<endl;
GraphBFS(G);
return 0;
}
邻接表存储结构
图片来自百度百科
typedef int EdgeType;
typedef char HeadName;
using namespace std;
const int MAX_SIZE = 1024;
typedef struct node{
int pos;
struct node *next;
}Node;
typedef struct headinfo{
HeadName name;
Node *head;
}Head;
typedef struct{
Head List[MAX_SIZE];
int vexnum, arcnum;
int kind;
}Graph;