Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class GraphAdjacentMatrix_TopologicalSort_DFS {
- private boolean adjMatrix[][];
- private int numVertices;
- private boolean visited[];
- public GraphAdjacentMatrix_TopologicalSort_DFS(int numVertices) {
- this.numVertices = numVertices;
- adjMatrix = new boolean[numVertices][numVertices];
- visited = new boolean[numVertices];
- }
- public void setEdge(int i, int j) {
- adjMatrix[i][j] = true;
- // adjMatrix[j][i] = true; // directed
- }
- public void delEdge(int i, int j) {
- adjMatrix[i][j] = false;
- // adjMatrix[j][i] = false; // directed
- }
- public boolean isEdge(int i, int j) {
- return adjMatrix[i][j];
- }
- public int first(int v1){
- boolean[] ary = this.adjMatrix[v1];
- int firstNeighborIndex = this.numVertices; // return n if none
- for (int i = 0; i < ary.length; i++) {
- if (ary[i] != false){
- firstNeighborIndex = i;
- break;
- }
- }
- return firstNeighborIndex;
- }
- public int next(int v1, int v2){
- boolean[] ary = this.adjMatrix[v1];
- int nextNeighborIndex = this.numVertices; // return n if none
- for (int i = v2 + 1; i < ary.length; i++) {
- if (ary[i] != false){
- nextNeighborIndex = i;
- break;
- }
- }
- return nextNeighborIndex; // return n if none
- }
- public void topSort_DFS(int v){
- topSort_DFS(this.adjMatrix, v);
- }
- public void topSort_DFS(boolean[][] graph, int v){
- Previsit(graph, v);
- // mark the current node
- visited[v] = true;
- // find neighbor
- for (int nextV = this.first(v); nextV < this.numVertices; nextV = this.next(v, nextV)) {
- if (!visited[nextV]){
- topSort_DFS(graph, nextV);
- }
- }
- Postvisit(graph, v);
- }
- private void Previsit(boolean[][] graph, int v) {
- // System.out.println("Previsit: " + v); // do not print anything for topologicalSort implemented in DFS
- }
- private void Postvisit(boolean[][] graph, int v) {
- System.out.println("Postvisit: " + v); // we will get an reverse order
- }
- public String toString() {
- StringBuilder s = new StringBuilder();
- for (int i = 0; i < numVertices; i++) {
- s.append(i + ": ");
- for (boolean j : adjMatrix[i]) {
- s.append((j?1:0) + " ");
- }
- s.append("\n");
- }
- return s.toString();
- }
- public static void main(String[] args) {
- GraphAdjacentMatrix_TopologicalSort_DFS gam = new GraphAdjacentMatrix_TopologicalSort_DFS(8);
- // directed graph
- gam.setEdge(1, 2);
- gam.setEdge(1, 3);
- gam.setEdge(2, 6);
- gam.setEdge(2, 5);
- gam.setEdge(2, 4);
- gam.setEdge(3, 4);
- gam.setEdge(4, 5);
- gam.setEdge(5, 7);
- System.out.println("DFS: ");
- gam.topSort_DFS( 1);
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement