c/c++ 图的实现

图的存储结构

struct graph{
    int node_nums;
    int edge_nums;
    int** edges;
};

创建图

graph* createGraph(){
    std::cout << "Input the count of graph's node and edges :  \n";
    int adj_nums,edge_nums;
    std::cin >> adj_nums >> edge_nums;
    graph* g = new graph;
    g->node_nums = adj_nums;
    g->edge_nums = edge_nums;
    g->edges = (int**)malloc(adj_nums * sizeof(int*));
    for(int i = 0;i < adj_nums;i++){
        g->edges[i] = (int*)malloc(adj_nums * sizeof(int));
        memset(g->edges[i], 0, sizeof(int) * adj_nums);
    }
    return g;
}

初始化图

void initGraph(graph* g){
   std::cout << "Input edges infomation: \n";
   int u,v,weight;
   for(int i = 0;i < g->edge_nums;i++){
       std::cin >> u >> v >> weight;
       g->edges[u][v] = weight;
       g->edges[v][u] = weight;
   }
}

销毁图

void deleteGraph(graph* g){
   if (g != NULL) {
       if(g->edges != NULL){
           for(int i = 0;i < g->node_nums;i++){
               free(g->edges[i]);
               g->edges[i] = NULL;
           }
       }else
           std::cout << "Free error!" << std::endl;
       free(g);
   }
}

显示图的矩阵表示

void showGraph(graph* g){
   for (int i = 0; i < g->node_nums; i++) {
       for (int j = 0; j < g->node_nums; j++) {
           std::cout << g->edges[i][j]  << " ";
       }
       std::cout << std::endl;
   }
}

广度搜索(非递归)

void bfs(graph* g,int start){
   int visited[g->node_nums];
   memset(visited, -1, sizeof(visited));
   std::queue<int>q;
   q.push(start);
   visited[start] = 0;
   while(q.size()){
       int front = q.front();
       q.pop();
       std::cout << front << "->";
       for(int i = 0;i < g->node_nums;i++){
           if(visited[i] == -1 && g->edges[front][i] != 0){
               q.push(i);
               visited[i] = 0;
           }
       }
   }
}

深度搜索(非递归)

void dfs(graph* g,int start){
   std::stack<int>s;
   int visited[g->node_nums];
   memset(visited, -1, sizeof(visited));
   s.push(start);
   visited[start] = 0;
   while (s.size()) {
       int top = s.top();
       s.pop();
       std::cout << top << "->";
       for(int i = 0;i < g->node_nums;i++){
           if(visited[i] == -1 && g->edges[top][i] != 0){
               s.push(i);
               visited[i] = 0;
           }
       }
   }
}

posted @ 2020-10-11 15:48  顾wenfan  阅读(283)  评论(0编辑  收藏  举报