#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
#define MAXSIZE 1000
using namespace std;
typedef int ElemType;
FILE *fp;
void InitFile()
{
bool e;
fopen_s(&fp, "data.txt", "r");
if (!fp) exit(ERROR);
return;
}
typedef bool Status;
基于 邻接表 表示的 深度优先搜索dfs 和 广度优先搜索bfs
/******
file input:
5
1 2
2 3
4 5
2 4
5 2
1 4
0 0
*******/
typedef struct node
{
int vertex;
struct node *link;
}Node, *node_ptr;
int ver_num;
node_ptr vertex;
Status InitGraph()
{
int a, b, n;//n个节点 对应 1.......n
fscanf_s(fp, "%d", &n);
ver_num = n;
vertex = (node_ptr)malloc(sizeof(Node)*(n + 1));
if (!vertex) exit(ERROR);
for (int i = 0; i <= n; i++){ vertex[i].vertex = i; vertex[i].link = NULL; }
while (fscanf_s(fp, "%d %d", &a, &b) && a && b)
{
if (a<1 || a>n || b<1 || b>n) exit(ERROR);
node_ptr c;
if (!(c = (node_ptr)malloc(sizeof(Node)))) exit(ERROR);
c->vertex = b;
c->link = vertex[a].link;
vertex[a].link = c;
if (!(c = (node_ptr)malloc(sizeof(Node)))) exit(ERROR);
c->vertex = a;
c->link = vertex[b].link;
vertex[b].link = c;
}
return OK;
}
void Output_node(node_ptr t)
{
printf("----> %d ", t->vertex);
if (!t->link) putchar(10);
}
void OutputGraph()
{
printf("节点个数为%d :从 1 到 %d\n", ver_num, ver_num);
printf("邻接表表示如下:\n");
int n = ver_num;
for (int i = 1; i <= n; i++)
{
printf("node : %d : ", i);
node_ptr t = vertex[i].link;
while (t)
{
Output_node(t);
t = t->link;
}
}
}
int visit[MAXSIZE];
void dfs(int i)
{
if (!visit[i])
{
printf("----> %d ", i);
visit[i] = 1;
node_ptr t = vertex[i].link;
while (t)
{
dfs(t->vertex);
t = t->link;
}
}
}
queue<node_ptr> Q;
void bfs(int i)
{
node_ptr t;
Q.push(vertex+i);
visit[(vertex + i)->vertex] = 1;
while (!Q.empty())
{
t = Q.front(); Q.pop();
printf("----> %d ", t->vertex);
//visit[t->vertex] = 1;
t = t->link;
while (t)
{
if (!visit[t->vertex]) {
Q.push(vertex + t->vertex);
visit[(vertex + t->vertex)->vertex] = 1;
}
t = t->link;
}
}
}
//by zhaoyang @ 2014.4.20
int main()
{
InitFile();
InitGraph();
OutputGraph();
printf("\ndfs搜索:\n");
for (int i = 1; i <= ver_num; i++)
{
memset(visit, 0, sizeof(visit));
dfs(i);
printf("\n");
}
printf("\nbfs搜索:\n");
for (int i = 1; i <= ver_num; i++)
{
memset(visit, 0, sizeof(visit));
bfs(i);
printf("\n");
}
fclose(fp);
return 0;
}