如何在Java中实现二分图?

时间:2010-08-03 18:03:26

标签: java data-structures graph bipartite

更新

到目前为止,有些答案建议使用邻接列表。在Java中,邻接列表如何? ......没有指针:)


我正在尝试用Java实现一个Bipartite Graph,从文件中分成两组信息。我找到了这个例子,它实际上完成了这项工作:

http://users.skynet.be/alperthereal/source_files/html/java/Bipartite.java.html

但是,我想实现我自己的版本...如果你看一下previous post of mine,你就会明白我为什么要自己做这个。

所以我必须读取一个文件,我可以从中轻松获得顶点数,但边数不是那么容易。一个示例行是“PersonA PersonB”,可以读作“PersonA说PersonB”。所以阅读这些内容......

"A says B"
"C says B"
"D says B"
"B says D"
"E says A & C"

...产生这种分组:

{A,D,C} and {B,E}.

我将如何实施这个二分图?什么是这项任务的好资源?在创建BipartiteGraph类时我应该考虑和思考什么(算法)...也许是遍历/排序算法?

5 个答案:

答案 0 :(得分:5)

使用邻接列表实现它应该非常简单。如果它是一个无向二分图,我可能会建议使用一个关联矩阵。

因此,您可以为每个节点提供一个链接列表数组,或者某种动态分配列表的数组。它应该使添加边缘相当自然,例如在你的例子中你有一个边缘:

人A->人B

然后你去对应于Person A的数组索引并推回对应于Persona B的索引:

[人A] = B人

那么也许你会得到另一个优势

Persona A->人C

然后你的索引看起来像是:

[女主持人A] = B人,C人

作为最后一个示例,这将是示例图的邻接列表:

[A] B

[B] D

[C] B

[D] B

[E] A,C

每个索引都有一个可从该节点到达的节点列表。

“在创建BipartiteGraph类时,我应该考虑和思考什么(算法)......也许是遍历/排序算法?”

这实际上取决于你想用图表做什么......

供参考:Similar Question with Code on Sun Forums

adjacency-list-of-a-directed-weighted-graph

答案 1 :(得分:3)

尝试: -

Bipartite.java

/*************************************************************************
 *  Compilation:  javac Bipartite.java
 *  Dependencies: Graph.java 
 *
 *  Given a graph, find either (i) a bipartition or (ii) an odd-length cycle.
 *  Runs in O(E + V) time.
 *
 *
 *************************************************************************/

/**
 *  The <tt>Bipartite</tt> class represents a data type for 
 *  determining whether an undirected graph is bipartite or whether
 *  it has an odd-length cycle.
 *  The <em>isBipartite</em> operation determines whether the graph is
 *  bipartite. If so, the <em>color</em> operation determines a
 *  bipartition; if not, the <em>oddCycle</em> operation determines a
 *  cycle with an odd number of edges.
 *  <p>
 *  This implementation uses depth-first search.
 *  The constructor takes time proportional to <em>V</em> + <em>E</em>
 *  (in the worst case),
 *  where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
 *  Afterwards, the <em>isBipartite</em> and <em>color</em> operations
 *  take constant time; the <em>oddCycle</em> operation takes time proportional
 *  to the length of the cycle.
 */
public class Bipartite {
    private boolean isBipartite;   // is the graph bipartite?
    private boolean[] color;       // color[v] gives vertices on one side of bipartition
    private boolean[] marked;      // marked[v] = true if v has been visited in DFS
    private int[] edgeTo;          // edgeTo[v] = last edge on path to v
    private Stack<Integer> cycle;  // odd-length cycle

    /**
     * Determines whether an undirected graph is bipartite and finds either a
     * bipartition or an odd-length cycle.
     * @param G the graph
     */
    public Bipartite(Graph G) {
        isBipartite = true;
        color  = new boolean[G.V()];
        marked = new boolean[G.V()];
        edgeTo = new int[G.V()];

        for (int v = 0; v < G.V(); v++) {
            if (!marked[v]) {
                dfs(G, v);
            }
        }
        assert check(G);
    }

    private void dfs(Graph G, int v) { 
        marked[v] = true;
        for (int w : G.adj(v)) {

            // short circuit if odd-length cycle found
            if (cycle != null) return;

            // found uncolored vertex, so recur
            if (!marked[w]) {
                edgeTo[w] = v;
                color[w] = !color[v];
                dfs(G, w);
            } 

            // if v-w create an odd-length cycle, find it
            else if (color[w] == color[v]) {
                isBipartite = false;
                cycle = new Stack<Integer>();
                cycle.push(w);  // don't need this unless you want to include start vertex twice
                for (int x = v; x != w; x = edgeTo[x]) {
                    cycle.push(x);
                }
                cycle.push(w);
            }
        }
    }

    /**
     * Is the graph bipartite?
     * @return <tt>true</tt> if the graph is bipartite, <tt>false</tt> otherwise
     */
    public boolean isBipartite() {
        return isBipartite;
    }

    /**
     * Returns the side of the bipartite that vertex <tt>v</tt> is on.
     * param v the vertex
     * @return the side of the bipartition that vertex <tt>v</tt> is on; two vertices
     *    are in the same side of the bipartition if and only if they have the same color
     * @throws UnsupportedOperationException if this method is called when the graph
     *    is not bipartite
     */
    public boolean color(int v) {
        if (!isBipartite)
            throw new UnsupportedOperationException("Graph is not bipartite");
        return color[v];
    }

    /**
     * Returns an odd-length cycle if the graph is not bipartite, and
     * <tt>null</tt> otherwise.
     * @return an odd-length cycle (as an iterable) if the graph is not bipartite
     *    (and hence has an odd-length cycle), and <tt>null</tt> otherwise
     */
    public Iterable<Integer> oddCycle() {
        return cycle; 
    }

    private boolean check(Graph G) {
        // graph is bipartite
        if (isBipartite) {
            for (int v = 0; v < G.V(); v++) {
                for (int w : G.adj(v)) {
                    if (color[v] == color[w]) {
                        System.err.printf("edge %d-%d with %d and %d in same side of bipartition\n", v, w, v, w);
                        return false;
                    }
                }
            }
        }

        // graph has an odd-length cycle
        else {
            // verify cycle
            int first = -1, last = -1;
            for (int v : oddCycle()) {
                if (first == -1) first = v;
                last = v;
            }
            if (first != last) {
                System.err.printf("cycle begins with %d and ends with %d\n", first, last);
                return false;
            }
        }

        return true;
    }

    /**
     * Unit tests the <tt>Bipartite</tt> data type.
     */
    public static void main(String[] args) {
        // create random bipartite graph with V vertices and E edges; then add F random edges
        int V = Integer.parseInt(args[0]);
        int E = Integer.parseInt(args[1]);
        int F = Integer.parseInt(args[2]);

        Graph G = new Graph(V);
        int[] vertices = new int[V];
        for (int i = 0; i < V; i++) vertices[i] = i;
        StdRandom.shuffle(vertices);
        for (int i = 0; i < E; i++) {
            int v = StdRandom.uniform(V/2);
            int w = StdRandom.uniform(V/2);
            G.addEdge(vertices[v], vertices[V/2 + w]);
        }

        // add F extra edges
        for (int i = 0; i < F; i++) {
            int v = (int) (Math.random() * V);
            int w = (int) (Math.random() * V);
            G.addEdge(v, w);
        }

        StdOut.println(G);

        Bipartite b = new Bipartite(G);
        if (b.isBipartite()) {
            StdOut.println("Graph is bipartite");
            for (int v = 0; v < G.V(); v++) {
                StdOut.println(v + ": " + b.color(v));
            }
        }
        else {
            StdOut.print("Graph has an odd-length cycle: ");
            for (int x : b.oddCycle()) {
                StdOut.print(x + " ");
            }
            StdOut.println();
        }
    }
}

答案 2 :(得分:1)

这是c#实现,但这个概念也可以在Java中使用。我使用Adjacency Matrix来表示图形。检查图中是否存在一个奇数周期。

如果该图中存在分区,则称为Bipartite,表示u和v其中(u union v)= Graph和(u intersection v)= null 如果你认为下图1,2,3,4,5,6,7是图G中的顶点,我们可以将左边的顶点(1,4,5,6)视为U和右边( 2,3,7)为V

现在考虑图中没有红色连接。您可以看到从u到v和v之间存在连接,因为它是一个无向图。但是在分区中没有任何关联。这就是我要使用的概念。

enter image description here

考虑如下图所示的图,它与上图相同,不同之处在于它更像树结构。在这种情况下,如果您可以看到备用级别上存在的节点1,3,5可以一起形成一个分区,2,4可以形成另一个分区。所以我们可以很容易地说这个图是BiPartite。如果同一级别的元素之间存在红色边缘怎么办?然后图表不是二分图。如果您可以修改BFS算法,我们就可以实现这一点。

enter image description here

这是代码。

   int[,] BPGraph = new int[7,7]{
                                    {0,1,0,1,0,0,0},
                                    {1,0,1,0,1,1,0},
                                    {0,1,0,1,0,0,1},
                                    {1,0,1,0,1,1,0},
                                    {0,1,0,1,0,0,1},
                                    {0,1,0,1,0,0,1},
                                    {0,0,1,0,1,1,0}
                                };

    int[] BPArray = new int[7] { 0, 0, 0, 0, 0, 0, 0 };

    public Boolean BiPartite()
    {
        Queue<int> VertexQueue = new Queue<int>();
        int level = 0;
        int nextlevel=0;
        Boolean BPFlg = true;

        VertexQueue.Enqueue(0);

        while(VertexQueue.Count!=0)
        {
            int current = VertexQueue.Dequeue();
            level = BPArray[current];

            if (level == 0)
                level = 1;

            if (level == 2)
                nextlevel=1;
            else
                nextlevel=2;

            if(BPArray[current]==0) 
                BPArray[current] = level;

            for (int i = 0; i < 7; i++)
            {
                if (BPGraph[current, i] == 1)
                {
                    if (BPArray[i] == 0)
                    {
                        BPArray[i] = nextlevel;
                        VertexQueue.Enqueue(i);
                    }
                    else if (BPArray[i] == level)
                    {
                        BPFlg = false;
                        break;
                    }
                }
            }
            if (!BPFlg)
                break;
        }
        return BPFlg;

    }

答案 3 :(得分:0)

有向图是连接节点A和B的边缘具有方向的图;如果从A到B有一条边,这并不意味着从B到A有一条边。在你的例子中,边有方向。 (B到D将是两个边,一个从B到D,一个从D到B.)

实现此目的的一种方法是以类似于链表的方式,其中节点在适当时具有彼此引用。回到您的示例,nodeA将引用nodeB,但不会反过来。 nodeE会引用nodeAnodeC,依此类推。你真的在创建一种(某种)数据结构,它具有节点和边缘的概念。有很多方法可以解决这个问题。

可能的Java实现将是一个名为AdjacencyList的类,其中Map<Vertex, List<Vertex>>包含一个顶点及其相邻顶点。然后,AdjacencyList可以在其地图上执行操作。

至于要记住的算法和事项,请查看Wikipedia上的二分图的属性,尤其是

  • 当且仅当它不包含奇数周期时,图是二分的。因此,二分图不能包含大小为3或更大的集团。
  • 每棵树都是二分的。
  • 具有偶数个顶点的循环图是二分的。

一个好的测试是实现一个2着色算法来确认图形确实是二分的。深度优先搜索,广度优先搜索是实施的良好练习。

答案 4 :(得分:0)

1。)选择随机节点。把它放在&#34;左边&#34;二分图的一面。

2.)选择与您在1中选择的节点相邻的所有节点,并将它们全部放在&#34;右侧&#34;侧。

3.)其余节点都属于&#34; left&#34;二分图的一面。

END