@@ -437,4 +437,104 @@ public class BreadthFirstPath extends AbstractPath{
437
437
}
438
438
System . out. println(sb. toString());
439
439
}
440
- ```
440
+ ```
441
+
442
+ ### 连通分量 Connection Component
443
+ > 无向图G 的极大连通子图称为G 的连通分量( Connected Component )。任何连通图的连通分量只有一个,即是其自身,非连通的无向图有多个连通分量。
444
+
445
+ * 接口
446
+ ```Java
447
+ public interface ConnectionComponent {
448
+ /**
449
+ * @Description: If v and w are connected.
450
+ * @param v
451
+ * @param w
452
+ * @return
453
+ */
454
+ public boolean connected (int v , int w );
455
+ /**
456
+ * @Description: Number of cc in current graph.
457
+ * @return
458
+ */
459
+ public int count ();
460
+ /**
461
+ * @Description: Identification of connection component.
462
+ * @param v
463
+ * @return
464
+ */
465
+ public int id (int v );
466
+ }
467
+ ```
468
+
469
+ * 抽象类
470
+ ```Java
471
+ public abstract class AbstractCC implements ConnectionComponent {
472
+ protected final Graph g;
473
+ public AbstractCC (Graph g ){
474
+ this . g = g;
475
+ }
476
+ }
477
+ ```
478
+
479
+ * 基于DFS 的实现
480
+ ```Java
481
+ public class DFSCC extends AbstractCC {
482
+ private boolean [] marked;
483
+ private int [] id;
484
+ private int count;
485
+ public DFSCC (Graph g ) {
486
+ super (g);
487
+ marked = new boolean [g. V ()];
488
+ id = new int [g. V ()];
489
+ for (int v = 0 ; v < g. V (); v++ ) // Traversal all of vertex if not accessed
490
+ if (! marked[v]){ // Current vertex is not accessed.
491
+ dfs(g, v);
492
+ count++ ;
493
+ }
494
+ }
495
+ @Override
496
+ public boolean connected (int v , int w ) {
497
+ return id[w] == id[v];
498
+ }
499
+ @Override
500
+ public int count () {
501
+ return this . count;
502
+ }
503
+ @Override
504
+ public int id (int v ) {
505
+ return id[v];
506
+ }
507
+ private void dfs (Graph g , int v ){
508
+ marked[v] = true ;
509
+ id[v] = count; // assign current count to this vertex as id.
510
+ for (int w : g. adj(v))
511
+ if (! marked[w])
512
+ dfs(g, w);
513
+ }
514
+ }
515
+ ```
516
+
517
+ * 测试
518
+ ```Java
519
+ public static void main(String [] args) throws FileNotFoundException {
520
+ Graph g = new UndirectedGraph (new FileInputStream (new File (" src/ca/mcmaster/chapter/four/graph/tinyG.txt" )));
521
+ DFSCC cc = new DFSCC (g);
522
+ int ccNum = cc. count();
523
+ System . out. println(" Number of cc: " + ccNum);
524
+ Bag<Integer > [] bag = new ListBag [ccNum]; // Create bag array to save all connection components.
525
+ for (int i = 0 ; i < ccNum; i++ )
526
+ bag[i] = new ListBag<> ();
527
+ for (int i = 0 ; i < g. V (); i++ )
528
+ bag[cc. id(i)]. add(i); // Add vertex into bag.
529
+ for (int i = 0 ; i < ccNum; i++ ){
530
+ StringBuilder sb = new StringBuilder (i + " : " );
531
+ for (int v : bag[i])
532
+ sb. append(v + " " );
533
+ System . out. println(sb. toString());
534
+ }
535
+ }
536
+ ```
537
+ > Number of cc: 3
538
+ > 0 : 6 5 4 3 2 1 0
539
+ > 1 : 8 7
540
+ > 2 : 12 11 10 9
0 commit comments