邻接矩阵
(1)邻接矩阵
-
邻接矩阵的C语言描述
-
基本运算的算法——建立无向网的邻接矩阵、求图中与顶点i邻接的第一个顶点、求图中顶点i相对于顶点j的下一个邻接点、若图G中存在顶点u,则返回该顶点在图中的位置、图的广度优先遍历、图的深度优先遍历
#include<iostream> #include<string.h> using namespace std; class Queue { public: int maxSize; int *data; int Front; int rear; int Count; Queue(int a = 10) { Front = 0; rear = 0; Count = 0; maxSize = a; data = new int[maxSize]; } void enQueue( int x) { if(Count > 0 && Front == rear) { cout<<"Queue is full"<<endl; return; } data[rear] = x; rear = (rear + 1) % maxSize; Count++; } void outQueue() { if(Count == 0) { cout <<"Queue is empty"<<endl; } int tem = data[Front]; Front = (Front + 1 )% maxSize; Count --; cout<<"out elem:"<<tem<<endl; } int isEmpty() { return Count == 0; } int returntop() { return data[Front]; } void makeEmpty() { Front = 0; rear = 0; Count = 0; } int readhead() { int tem = data[Front]; return tem; } void printQueue() { int j = Front; for(int i = 0 ; i < Count ; i++ ) { cout<<data[j]<<" "; j = ( j + 1 )%maxSize; } } int getlength() { return Count; } }; class Adacency_Matrix: public Queue { public: int n; int **matrix; int * visit; Adacency_Matrix() { cout<<"please input point number"<<endl; cin>>n; visit = new int [n]; memset(visit , 0 , sizeof(int)*n); matrix = new int* [n]; for(int i = 0 ; i < n ; i ++) { matrix[i] = new int [n]; } } void creat() { for(int i = 0 ; i < n ; i ++) { for(int j = 0 ; j < n ; j ++) { cin>>matrix[i][j]; } } } void qiudingdian()//求图中与顶点i邻接的第一个顶点 { cout<<"请输入顶点编号"<<endl; int tem; cin>>tem; for(int i = 0 ; i < n ; i++) { if(matrix[tem][i]!=0&&matrix[tem][i]!=-1) { cout<<"相邻的顶点是:"<<i<<endl; break; } } } void qiuweizhi()//若图G中存在顶点u,则返回该顶点在图中的位置 { cout<<"请输入顶点编号"<<endl; int tem; cin>>tem; if(tem>n) { cout<<"这个顶点不存在"<<endl; } else { cout<<"与它相邻的顶点有"<<endl; for(int i = 0 ; i < n ; i ++) { if(matrix[tem][i]!=0&&matrix[tem][i]!=-1) { cout<<i<<endl; } } } } void bfs(Queue a) { int z = 0; a.enQueue(z); for(int i = 0 ; i < n ; i ++) { visit[i] = 0; } visit [ 0 ] = 1; while(!a.isEmpty()) { int j = a.returntop(); cout<<"与"<<j<<"相邻的节点有:"<<endl; for(int i = 0 ; i < Adacency_Matrix::n ; i ++) { if(matrix[j][i]!=0&&matrix[j][i]!=-1) { cout<<i<<" "; if(visit[i]==0) { a.enQueue(i); visit[i] = 1; } } } cout<<endl; a.outQueue(); } } void dfs(int u) { visit [ u ] = 1; cout<<u<<endl; for(int i = 0 ; i < Adacency_Matrix::n ; i++) { if(matrix[u][i]!=0&&matrix[u][i]!=-1&&visit[i]==0) { visit[i] = 1; dfs(i); } } } }; int main() { Queue dusk; Adacency_Matrix duskcl; duskcl.creat(); cout<<"starting bfs!!!!!!!!!!!!!!!!!!!!!"<<endl; duskcl.bfs(dusk); memset(duskcl.visit,0,sizeof(int)*duskcl.n); int tem = 0; cout<<endl; cout<<"starting dfs!!!!!!!!!!!!!!!!!!!!!"<<endl; duskcl.dfs(tem); }