zoukankan      html  css  js  c++  java
  • C++图的ADT实现(邻接矩阵)

    /*
     * description:        图的ADT实现(邻接矩阵)
     * writeby:            Nick
     * date:            2012-10-25 23:32
     *
     */
    
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    struct Edge
    {
        int v, w;
        Edge(int v=-1, int w=-1) : v(v), w(w) {}
    };
    
    class Graph
    {
        private:
            int vcount, ecount;        //记录顶点总数,边总数
            bool digraph;            //标记是否有向图
            vector <vector <bool> > adj;        //邻接矩阵数组
        public:
            Graph(int V, bool di = false) : adj(V), vcount(V), digraph(di)
            {
                for(int i=0; i<V; i++)
                    adj[i].assign(V, false);    // V * V 临接矩阵的大小 
            }
            //~Graph();
            int V() const {return vcount;}
    
            int E() const {return ecount;}
    
            bool directed() const { return digraph; }
    
            int insert(Edge e)
            {
                int v=e.v, w=e.w;
                if(adj[v][w] == false) ecount++;
                adj[v][w] = true;                        // v-w 做标记
                if(!digraph) adj[w][v] = true;            //无向图中 w-v 也做标记
            }
    
            int remove(Edge e)
            {
                int v=e.v, w=e.w;
                if(adj[v][w]==true) ecount--;
                adj[v][w] = false;
                if(!digraph) adj[w][v] = false;
            }
    
            bool edge(int v, int w) const { return adj[v][w]; }
    
            class adjIterator;
            friend class adjIterator;
    };
    
    class Graph::adjIterator        //临接矩阵表示的迭代器
    {
        private:
            const Graph &G;
            int i, v;
        public:
            adjIterator(const Graph& G, int v) : G(G), v(v), i(-1)
            {}
    
            int begin()
            {
                i=-1;
                return next();
            }
    
            int next()
            {
                for(i++; i<G.V(); i++)
                    if(G.adj[v][i] == true) return i;    //adj[v][0..v-1] 记录着 v 到 0..v 各点是否相连
                return -1;    //没有找到
            }
    
            int end()
            {
                return i>=G.V();
            }
    };
    
    int main()
    {
        return 0;
    }
  • 相关阅读:
    1026 Table Tennis (30)
    1029 Median
    1025 PAT Ranking (25)
    1017 Queueing at Bank (25)
    1014 Waiting in Line (30)
    1057 Stack (30)
    1010 Radix (25)
    1008 Elevator (20)
    字母大小写转换
    Nmap的基础知识
  • 原文地址:https://www.cnblogs.com/wouldguan/p/2740404.html
Copyright © 2011-2022 走看看