Guest User

Graph

a guest
Dec 11th, 2013
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. class Graph<E> {
  2.  
  3.     int num_nodes;
  4.     GraphNode<E> adjList[];
  5.  
  6.     @SuppressWarnings("unchecked")
  7.     public Graph(int num_nodes, E[] list) {
  8.         this.num_nodes = num_nodes;
  9.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  10.         for (int i = 0; i < num_nodes; i++)
  11.             adjList[i] = new GraphNode<E>(i, list[i]);
  12.     }
  13.  
  14.     @SuppressWarnings("unchecked")
  15.     public Graph(int num_nodes) {
  16.         this.num_nodes = num_nodes;
  17.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  18.         for (int i = 0; i < num_nodes; i++)
  19.             adjList[i] = new GraphNode<E>(i, (E) new Object());
  20.     }
  21.  
  22.     int adjacent(int x, int y) {
  23.         // proveruva dali ima vrska od jazelot so
  24.         // indeks x do jazelot so indeks y
  25.         return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
  26.     }
  27.  
  28.     void addEdge(int x, int y) {
  29.         // dodava vrska od jazelot so indeks x do jazelot so indeks y
  30.         if (!adjList[x].containsNeighbor(adjList[y])) {
  31.             adjList[x].addNeighbor(adjList[y]);
  32.         }
  33.     }
  34.  
  35.     void deleteEdge(int x, int y) {
  36.         adjList[x].removeNeighbor(adjList[y]);
  37.     }
  38.  
  39.     void dfsNonrecursive(int node) {
  40.         boolean visited[] = new boolean[num_nodes];
  41.         for (int i = 0; i < num_nodes; i++)
  42.             visited[i] = false;
  43.         visited[node] = true;
  44.         System.out.println(node + ": " + adjList[0].getInfo());
  45.         Stack<Integer> s = new Stack<Integer>();
  46.         s.push(node);
  47.  
  48.         GraphNode<E> pom;
  49.  
  50.         while (!s.isEmpty()) {
  51.             pom = adjList[s.peek()];
  52.             GraphNode<E> tmp = null;
  53.             for (int i = 0; i < pom.getNeighbors().size(); i++) {
  54.                 tmp = pom.getNeighbors().get(i);
  55.                 if (!visited[tmp.getIndex()])
  56.                     break;
  57.             }
  58.             if (tmp != null && !visited[tmp.getIndex()]) {
  59.                 visited[tmp.getIndex()] = true;
  60.                 System.out.println(tmp.getIndex() + ": " + tmp.getInfo());
  61.                 s.push(tmp.getIndex());
  62.             } else
  63.                 s.pop();
  64.         }
  65.     }
  66.  
  67.     @Override
  68.     public String toString() {
  69.         String ret = new String();
  70.         for (int i = 0; i < this.num_nodes; i++)
  71.             ret += i + ": " + adjList[i] + "\n";
  72.         return ret;
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment