|
| 1 | +package graph_bridges; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.util.TreeSet; |
| 6 | +import java.util.Scanner; |
| 7 | + |
| 8 | + |
| 9 | +/// 暂时只支持无向无权图 |
| 10 | +public class Graph { |
| 11 | + |
| 12 | + private int V; |
| 13 | + private int E; |
| 14 | + private TreeSet<Integer>[] adj; |
| 15 | + |
| 16 | + public Graph(String filename) { |
| 17 | + |
| 18 | + File file = new File(filename); |
| 19 | + |
| 20 | + try (Scanner scanner = new Scanner(file)) { |
| 21 | + |
| 22 | + V = scanner.nextInt(); |
| 23 | + if (V < 0) throw new IllegalArgumentException("V must be non-negative"); |
| 24 | + adj = new TreeSet[V]; |
| 25 | + for (int i = 0; i < V; i++) |
| 26 | + adj[i] = new TreeSet<Integer>(); |
| 27 | + |
| 28 | + E = scanner.nextInt(); |
| 29 | + if (E < 0) throw new IllegalArgumentException("E must be non-negative"); |
| 30 | + |
| 31 | + for (int i = 0; i < E; i++) { |
| 32 | + int a = scanner.nextInt(); |
| 33 | + validateVertex(a); |
| 34 | + int b = scanner.nextInt(); |
| 35 | + validateVertex(b); |
| 36 | + |
| 37 | + if (a == b) throw new IllegalArgumentException("Self Loop is Detected!"); |
| 38 | + if (adj[a].contains(b)) throw new IllegalArgumentException("Parallel Edges are Detected!"); |
| 39 | + |
| 40 | + adj[a].add(b); |
| 41 | + adj[b].add(a); |
| 42 | + } |
| 43 | + } catch (IOException e) { |
| 44 | + e.printStackTrace(); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + public void validateVertex(int v) { |
| 49 | + if (v < 0 || v >= V) |
| 50 | + throw new IllegalArgumentException("vertex " + v + "is invalid"); |
| 51 | + } |
| 52 | + |
| 53 | + public int V() { |
| 54 | + return V; |
| 55 | + } |
| 56 | + |
| 57 | + public int E() { |
| 58 | + return E; |
| 59 | + } |
| 60 | + |
| 61 | + public boolean hasEdge(int v, int w) { |
| 62 | + validateVertex(v); |
| 63 | + validateVertex(w); |
| 64 | + return adj[v].contains(w); |
| 65 | + } |
| 66 | + |
| 67 | + public Iterable<Integer> adj(int v) { |
| 68 | + validateVertex(v); |
| 69 | + return adj[v]; |
| 70 | + } |
| 71 | + |
| 72 | + public int degree(int v) { |
| 73 | + validateVertex(v); |
| 74 | + return adj[v].size(); |
| 75 | + } |
| 76 | + |
| 77 | + @Override |
| 78 | + public String toString() { |
| 79 | + StringBuilder sb = new StringBuilder(); |
| 80 | + |
| 81 | + sb.append(String.format("V = %d, E = %d\n", V, E)); |
| 82 | + for (int v = 0; v < V; v++) { |
| 83 | + sb.append(String.format("%d : ", v)); |
| 84 | + for (int w : adj[v]) |
| 85 | + sb.append(String.format("%d ", w)); |
| 86 | + sb.append('\n'); |
| 87 | + } |
| 88 | + return sb.toString(); |
| 89 | + } |
| 90 | + |
| 91 | + public static void main(String[] args) { |
| 92 | + |
| 93 | + Graph g = new Graph("graph_bridges/g.txt"); |
| 94 | + System.out.print(g); |
| 95 | + } |
| 96 | +} |
0 commit comments