图的建立、存储(邻接矩阵,邻接表)

邻接矩阵

#include <stdio.h>
#include <string.h>

#define MAX_N 500

typedef struct Graph {
    int mat[MAX_N][MAX_N];
    int n;
}Graph;

void init(Graph *g, int len) {
    g->n = len;
    memset(g->mat, 0, sizeof(g->mat));
}

void insert(Graph *g, int a, int x, int y) {
    if (x < 0 || y < 0 || x >= g->n || y >= g->n) return ;
    g->mat[x][y] = 1;
    g->mat[y][x] = !!a;
}

void output(Graph *g) {
    for (int i = 0; i < g->n; ++i) {
        for (int j = 0; j < g->n; ++j) printf("%d ", g->mat[i][j]);
        printf("
");
    }
}

int main() {
    int n, m, x, y;
    short a;
    Graph graph;
    // 输入节点个数, 边个数
    scanf("%d%d", &n, &m);
    init(&graph, n);
    for (int i = 0; i < m; i++) {
        // 输入x连向n的边(范围为n-1), a != 0 无向边 a = 0有向边
        scanf("%d%d%d", &a, &x, &y); 
        // 创建边
        insert(&graph, a, x, y);
    }
    output(&graph);
    return 0;
}

邻接表

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_N 10000

typedef struct Node {
    int vertex;
    struct Node *next;
} Node, *LinkedList;

LinkedList insert_node(LinkedList head, int index) {
    Node *node = (Node *)malloc(sizeof(Node));
    node->vertex = index;
    node->next = head;
    head = node;
    return head;
}

typedef struct Graph {
    LinkedList edges[MAX_N];
    int n;
} Graph;

void init(Graph *g, int n) {
    g->n = n;
    for (int i = 0; i < g->n; ++i) {
        g->edges[i] = NULL;
    }
}

void insert(Graph *g, int a, int x, int y) {
    if (x < 0 || x >= g->n || y < 0 || y >= g->n) {
        return ;
    }
    g->edges[x] = insert_node(g->edges[x], y); 
    if (a) g->edges[y] = insert_node(g->edges[y], x); 
}

void output(Graph *g) {
    for (int i = 0; i < g->n; ++i) {
        printf("%d:", i);
        for (Node *j = g->edges[i]; j != NULL; j = j->next) {
            printf("%d ", j->vertex);
        }
        printf("
");
    }
}

void clear(Graph *g) {
    for (int i = 0; i < g->n; ++i) {
        Node *head = g->edges[i];
        while (head != NULL) {
            Node *delete_node = head;
            head = head->next;
            free(delete_node);
        }
    }
    free(g);
}

int main() {
    int n, m, x, y, a;
    // 输入节点个数, 边个数
    scanf("%d %d", &n, &m);
    Graph *graph = (Graph *)malloc(sizeof(Graph));
    init(graph, n);
    for (int i = 0; i < m; ++i) {
        // 输入x连向n的边(范围为n-1), a != 0 无向边 a = 0有向边
        scanf("%d%d%d", &a, &x, &y);
        // 创建边
        insert(graph, a, x, y);
    }
    output(graph);
    clear(graph);
    return 0;
}
原文地址:https://www.cnblogs.com/hhhahh/p/14045811.html