十一、圖的存儲---(3)鄰接矩陣的構造和使用

摘自計蒜客:http://www.jisuanke.com/course/35/7195

//以下主要針對有向圖,如果遇到無向圖的情況,將每條無向邊對應到有向圖中的正反兩條邊就可以了。


#include <iostream>
#include <cstring>
using namespace std;

class Graph {
private:
    int **mat;
    int n;

public:
    Graph(int input_n) {
        n = input_n;
        mat = new int*[n];
        for (int i = 0; i < n; ++i) {
            mat[i] = new int[n];
            memset(mat[i], 0, sizeof(int) * n);
        }
    }

    ~Graph() {
        for (int i = 0; i< n; ++i) {
            delete[] mat[i];
        }
        delete[] mat;
    }

    void insert(int x, int y) {
        mat[x][y] = 1;
    }

    void output() {
        for (int i=0; i<n; i++) {
            for (int j=0; j<n; j++) {
                cout << mat[i][j] << " ";
            }
            cout << endl;
        }
    }
};

int main() {
    int n, m, x, y;
    cin >> n >> m;
    Graph g(n);
    for (int i = 0; i < m; ++i) {
        cin >> x >> y;
        g.insert(x, y);
    }
    g.output();
    return 0;
}


發佈了6 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章