| package com.tiffanyiong; |
| |
| import java.util.ArrayList; |
| import java.util.Arrays; |
| import java.util.List; |
| |
| |
| public class Main { |
| public static void main(String[] args){ |
| int n = 5; |
| String vertices[] = {"A", "B", "C", "D", "E"}; |
| |
| Graph graph = new Graph(n); |
| |
| for (String vertex : vertices) { |
| graph.insertVertex(vertex); |
| } |
| |
| |
| graph.insertEdge(0, 1, 1); |
| graph.insertEdge(0, 2, 1); |
| graph.insertEdge(1, 2, 1); |
| graph.insertEdge(1, 3, 1); |
| graph.insertEdge(1, 4, 1); |
| |
| |
| graph.showGraph(); |
| } |
| } |
| |
| class Graph { |
| |
| public ArrayList<String> vertexList; |
| public int[][] edges; |
| public int numsOfEdges; |
| |
| |
| |
| |
| public Graph(int n) { |
| edges = new int[n][n]; |
| vertexList = new ArrayList<String>(n); |
| numsOfEdges = 0; |
| } |
| |
| |
| |
| public int getNumOfVertex(){ |
| return vertexList.size(); |
| } |
| |
| |
| public void showGraph() { |
| for (int[] link : edges) { |
| System.out.println(Arrays.toString(link)); |
| } |
| } |
| |
| |
| public int getNumOfEdges(){ |
| return numsOfEdges; |
| } |
| |
| |
| public String getValueByIndex(int i ) { |
| return vertexList.get(i); |
| } |
| |
| |
| public int getWeight(int v1, int v2) { |
| return edges[v1][v2]; |
| } |
| |
| |
| |
| public void insertVertex(String vertex){ |
| vertexList.add(vertex); |
| } |
| |
| |
| |
| |
| |
| public void insertEdge(int v1, int v2, int weight){ |
| edges[v1][v2] = weight; |
| |
| edges[v2][v1] = weight; |
| numsOfEdges++; |
| |
| } |
| } |