Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.aids.graph;
- /**
- * Created by spike994 on 08.05.15.
- */
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Random;
- public class MatrixGraph implements Graph {
- private int V;
- private int E;
- public boolean[][] adjacencyMatrix;
- private Random rand = new Random();
- /**
- *
- * @param V amount of vertexes
- * @param param density
- */
- public MatrixGraph(int V, double param) {
- this.V = V;
- this.setE((int) (((V * (V - 1)) / 2)*param));
- this.adjacencyMatrix = new boolean[V][V];
- for (int i = 0; i < ((V * (V - 1)) / 2)*param; i++) {
- int v1 = rand.nextInt(V);
- int v2 = rand.nextInt(V);
- if (v1 == v2) {
- i--;
- } else {
- if (!adjacencyMatrix[v1][v2]) {
- adjacencyMatrix[v1][v2] = true;
- adjacencyMatrix[v2][v1] = true;
- } else {
- i--;
- }
- }
- }
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("\n");
- for (int v = 0; v < V; v++) {
- sb.append("||" + v + "||");
- for (int w = 0; w < V; w++) {
- if (adjacencyMatrix[v][w]) {
- sb.append(" [1] ");
- } else
- sb.append(" [0] ");
- }
- sb.append("\n");
- }
- return sb.toString();
- }
- public Integer[] getAdjacentVertexes(int v) {
- LinkedList<Integer> list = new LinkedList<Integer>();
- for (int i = 0; i < V; i++) {
- if (adjacencyMatrix[v][i]) {
- list.add(i);
- }
- }
- return list.toArray(new Integer[1]);
- }
- public ListGraph toListGraph() {
- @SuppressWarnings("unchecked")
- List<Integer>[] adjacencyList = new List[this.V];
- for (int i = 0; i < this.V; i++) {
- adjacencyList[i] = new LinkedList<Integer>();
- for (int j = 0; j < this.V; j++) {
- if (adjacencyMatrix[i][j]){
- adjacencyList[i].add(j);
- }
- }
- }
- return new ListGraph(this.V, adjacencyList);
- }
- public int getE() {
- return E;
- }
- public void setE(int e) {
- E = e;
- }
- public int getV(){
- return V;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment