Struktur Data 2 Graph
Berikut merupakan code program struktur data 2 tentang Graph.
berikut merupakan code untuk BFS :
Berikut merupakan code untuk DFS :
Vertex[] vertexList;final int maxVertex = 10;int countVertex;int[][] adjacencyMatrix;public Graph() {vertexList = new Vertex[maxVertex];adjacencyMatrix = new int[maxVertex][maxVertex];countVertex = 0;for (int i = 0; i < vertexList.length; i++) {for (int j = 0; j < vertexList.length; j++) {adjacencyMatrix[i][j] = 0;}}}public void addVertex(char label) {vertexList[countVertex] = new Vertex(label);countVertex++;}public void addEdge(char start, char end, int weight) {adjacencyMatrix[indexVertex(start)][indexVertex(end)] = weight;adjacencyMatrix[indexVertex(end)][indexVertex(start)] = weight;}@Overridepublic String toString() {String temp = " ";for (int i = 0; i < countVertex; i++) {for (int j = 0; j < countVertex; j++) {temp = temp + adjacencyMatrix[i][j] + " ";}temp += "\n";}return temp;}public int indexVertex(char label) {for (int i = 0; i < vertexList.length; i++) {if (vertexList[i].getLabel() == label) {return i;}}return -1;}
berikut merupakan code untuk BFS :
public void bfs(){int seed = 0;Queue q = new Queue();
q.enqueue(seed);while(!q.isEmpty()){int bantu2 = q.dequeue();while(vertexList[bantu2].flagVisited == false){System.out.println(vertexList[bantu2].getLabel()+" ");vertexList[bantu2].flagVisited = true;}for (int i = 0; i < countVertex; i++) {if(adjacencyMatrix[bantu2][i]==1 && !vertexList[i].flagVisited){q.enqueue(i);}}}
Berikut merupakan code untuk DFS :
public void dfs() {int seed = 0;Stack s = new Stack();s.push(seed);while (!s.isEmpty()) {int bantu = s.pop();if (vertexList[bantu].flagVisited == false) {System.out.println(vertexList[bantu].getLabel()+ " ");vertexList[bantu].flagVisited = true;}for (int i = countVertex-1; i >=0; i--) {if(adjacencyMatrix[bantu][i]==1 && !vertexList[i].flagVisited){s.push(i);}}}}
Komentar