前几天有小朋友求助关于图的邻接表示及深搜,记得一年前的我学数据结构也搞的乱七八糟的。我就顺便学下吧,网上的代码都好规范的感觉,读那些代码的能力不够,自己把那些代码简化了下。
非常感谢那些小朋友给我这么一次机会。
/* 无向图的邻接表表示 */
#include <iostream>
#include <stdio.h>
#define N 50
using namespace std;
/************************************************************************/
/* headNode: h_vex + firstnode
该头节点编号 后继结点(链)指针
Node: No + nextnode
头结点的下标 下一结点指针
Graph: vertices + vernum arcnum
表 结点数 边数
/************************************************************************/
struct Node {
int No;
Node *nextnode;
};
struct headNode {
int h_vex;
Node *firstnode;
};
struct Graph {
headNode vertices[N];
int vexnum, arcnum;
};
void createGraph (Graph *G)
{
scanf ("%d %d", &(*G).vexnum, &(*G).arcnum);//***************************INPUT 点数 边数
/* 初始化表头 */
for (int i = 1;i <= (*G).vexnum;i ++)
{
(*G).vertices[i].h_vex = i;
(*G).vertices[i].firstnode = NULL;
}
/* 随着边的输入 把点一个个插进去 */
for (int a, b, i = 1;i <= (*G).arcnum;i ++)
{
// an arc from (vertex)a to vertex(b)
scanf ("%d %d", &a, &b); //***************************INPUT 边信息
Node *tmp = new Node;// Node *tmp = (Node *)malloc(sizeof(Node));
tmp->No = b;
tmp->nextnode = G->vertices[a].firstnode;
G->vertices[a].firstnode = tmp;
tmp = (Node *)malloc(sizeof(Node));
tmp->No = a;
tmp->nextnode = G->vertices[b].firstnode;
G->vertices[b].firstnode = tmp;
}
}
void graphDFS (Graph G, int start, int *record)
{
Node *tmp = new Node;
record[start] = 1; // 经过记录为 1
printf ("%d->", start);
tmp = G.vertices[start].firstnode;
while (tmp != NULL)
{
if (!record[tmp->No])
graphDFS (G, tmp->No,record);
printf ("\n");
tmp = tmp->nextnode;
}
}
void travelGraph (Graph *G, int start)
{
/* 记录是否经过 */
int done[N];
// initial
for (int i = 1;i <= G->vexnum;i ++)
done[i] = 0;
/* 遍历 */
graphDFS (*G, start, done);
/* 检验是否全部遍历 */
for (int i = 0;i <= G->vexnum;i ++)
if (!done[i])
printf("cannot travel all the point --> %d", i);
}
int main ()
{
//freopen ("in.txt", "r", stdin);
Graph *g = new Graph;// g = (Graph *)malloc(sizeof(Graph));
createGraph (g);
/* Travel from Node x */
int x;
scanf("%d", &x); //******************************INPUT 开始遍历的位置
travelGraph (g, x);
}
/* 测试数据
6 7
1 6
1 5
1 2
3 6
4 3
4 2
3 2
3
*/