Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Write a description of class Graph here.
- *
- * Samuel Berkat Hulu
- * @version 5.0
- */
- class Graph
- {
- private final int numNodes;
- private final boolean direct;
- private final boolean weight;
- private final float[][] matrix;
- private final boolean[][] isMatrix;
- Graph(int num, boolean direct, boolean weight)
- {
- this.direct = direct;
- this.weight = weight;
- this.numNodes = num;
- matrix = new float[num][num];
- isMatrix = new boolean[num][num];
- }
- public void addEdge(int start, int end)
- {
- int addValue = 1;
- if (weight)
- addValue = 0;
- matrix[start][end] = addValue;
- isMatrix[start][end] = true;
- if (!direct)
- {
- matrix[end][start] = addValue;
- isMatrix[end][start] = true;
- }
- }
- public void addEdge(int start, int end, float the_weight)
- {
- float addValue = the_weight;
- if (!weight)
- addValue = 1;
- matrix[start][end] = addValue;
- isMatrix[start][end] = true;
- if (!direct)
- {
- matrix[end][start] = addValue;
- isMatrix[end][start] = true;
- }
- }
- public void printMatrix()
- {
- for (int i = 0; i < numNodes; i++)
- {
- for (int j = 0; j < numNodes; j++)
- {
- if (isMatrix[i][j])
- System.out.format("%8s", matrix[i][j]);
- else
- System.out.format("%8s", "/ ");
- }
- System.out.println();
- }
- }
- public void printEdges()
- {
- for (int i = 0; i < numNodes; i++)
- {
- System.out.print("Node " + i + " is connected to: ");
- for (int j = 0; j < numNodes; j++)
- {
- if (isMatrix[i][j])
- System.out.print(j + " ");
- }
- System.out.println();
- }
- }
- public boolean hasEdge(int start, int end)
- {
- return isMatrix[start][end];
- }
- }
- public class Main
- {
- public static void main(String[] args)
- {
- Graph graph = new Graph(6, false, true);
- graph.addEdge(0, 1, 19);
- graph.addEdge(0, 2, 10);
- graph.addEdge(0, 3, 7);
- graph.addEdge(0, 4, 2);
- graph.addEdge(0, 5, 11);
- graph.addEdge(1, 2, 3);
- graph.addEdge(1, 3);
- graph.addEdge(1, 4);
- graph.addEdge(2, 3);
- graph.addEdge(3, 4);
- graph.addEdge(4, 5);
- graph.printMatrix();
- System.out.println();
- System.out.println();
- graph.printEdges();
- System.out.println();
- System.out.println("Does an edge from 1 to 5 exist?");
- if (graph.hasEdge(0,1))
- System.out.println("Yes");
- else
- System.out.println("No");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement