额,今天完成了项目的说明文档,正式结束项目,撒花
邻接矩阵
板子:
#include<iostream>
using namespace std;
const int maxn=105;
int adj[maxn][maxn]={0}; //定义邻接矩阵
int x,y; //输入两条边
int n,m; //供输入n对边 ,m个顶点 (x,y <= m)
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>x>>y;
adj[x-1][y-1]=1;
adj[y-1][x-1]=1;
}
for(int i=0;i<m;i++){
for(int j=0;j<m;j++){
cout<<adj[i][j]<<' ';
}
cout<<endl;
}
return 0;
}
邻接表
板子
#include<stdio.h>
#include<iostream>
#include<malloc.h>
#define maxSize 1000
using namespace std;
typedef struct ArcNode {
int adjvex;
struct ArcNode *nextarc;
} ArcNode;
typedef struct {
int data;
ArcNode *firstarc;
} Vnode;
//可以利用结构体整体结构,也可以拆分结构体变为单独搜索
typedef struct {
Vnode adjlist[maxSize];
int n, e;
} AGraph;
AGraph *graph;
//插入链表末尾
void insertNode(ArcNode *node, ArcNode *newNode) {
ArcNode *p = node;
while(p->nextarc != NULL) {
p = p->nextarc;
}
p->nextarc = newNode;
}
void create() {
graph = (AGraph*)malloc(sizeof(AGraph));
cout << "输入顶点的数目: " << endl;
cin >> graph->n;
cout << "输入图中边的数目: " << endl;
cin >> graph->e;
int u = -1, v = -1;
for(int i = 0; i < graph->n; i++) {
graph->adjlist[i].firstarc = NULL;
}
ArcNode *node;
for(int i = 0; i < graph->e; i++) {
cout<<"请输入联通点A与B"<<endl;
cin >> u >> v ;
node = (ArcNode *)malloc(sizeof(ArcNode));
node->adjvex = v;
node->nextarc = NULL;
graph->adjlist[u].data = u;
if(graph->adjlist[u].firstarc == NULL) {
//边
graph->adjlist[u].firstarc = node;
} else {
//插入边
insertNode(graph->adjlist[u].firstarc, node);
}
}
}
void travseTree() {
for(int i = 0; i < graph->n; i++) {
if(graph->adjlist[i].firstarc != NULL) {
cout <<"与"<< i << "连接的点有:";
ArcNode *p = graph->adjlist[i].firstarc;
while(p != NULL) {
cout << p->adjvex << " ";
p = p->nextarc;
}
cout << endl;
}
}
}
int main(void) {
create();
travseTree();
return 0;
}
BFS
板子
/**
* 返回合适的检索数据
*/
int BFS(Node root, Node target)
{
Queue<Node> queue; //创建队列
int step = 0; // 当前队列的步骤点
// initialize
add root to queue;
// BFS
while (queue is not empty)
{
step = step + 1;
//步数逐渐增加
int size = queue.size();
for (int i = 0; i < size; ++i)
{
Node cur = the first node in queue;
if cur is target
return step - 1;
for (Node next : the neighbors of cur)
{//这里常用一个二维方向数组实现
add next to queue;
}
remove the first node from queue;
}
}
return -1; //出错返回值
}