手记

C/C++算法(邻接矩阵 (类版) )

/*
邻接矩阵 (类版)
作者:Zhihang 
*/

#include<iostream>
#include<vector>

using namespace std;

class Tu{

private:
    int m,n;
    bool youWuQuan;
public:
    vector< vector<int> > g;    
    Tu(int n,bool youWuQuan){
        this->n=n;
        this->youWuQuan=youWuQuan;
        this->m=0;
        for(int i=0;i<n;i++)
            g.push_back( vector<int>() );
    }

    ~Tu(){
    }

    bool isLian(int v,int m){
        for(int i=0;i<g[v].size();i++){
            if(g[v][i]==m)
                return true;
        }   
        return false;
    } 

    bool addEgen(int v,int m){
        if(isLian(v,m) )
            return false;

        g[v].push_back(m);
        if(!youWuQuan){
            g[m].push_back(v);
        }
        m++;
        return true;
    }
};
int main(){
    const int n=5;
    Tu tu(n,false);
    tu.addEgen(1,3);
    tu.addEgen(1,4);
    tu.addEgen(2,5);
    tu.addEgen(2,4);
    tu.addEgen(3,5); 

    for(int i=1;i<=n;i++){
        cout<<i<<": ";
        for(int j=0;j<tu.g[i].size();j++){
            cout<<tu.g[i][j]<<" ";
        }
        cout<<endl;
    }   
    return 0;
}
0人推荐
随时随地看视频
慕课网APP