Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Graph<E> {
- int num_nodes;
- GraphNode<E> adjList[];
- @SuppressWarnings("unchecked")
- public Graph(int num_nodes, E[] list) {
- this.num_nodes = num_nodes;
- adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
- for (int i = 0; i < num_nodes; i++)
- adjList[i] = new GraphNode<E>(i, list[i]);
- }
- @SuppressWarnings("unchecked")
- public Graph(int num_nodes) {
- this.num_nodes = num_nodes;
- adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
- for (int i = 0; i < num_nodes; i++)
- adjList[i] = new GraphNode<E>(i, (E) new Object());
- }
- int adjacent(int x, int y) {
- return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
- }
- void addEdge(int x, int y) {
- if (!adjList[x].containsNeighbor(adjList[y])) {
- adjList[x].addNeighbor(adjList[y]);
- }
- }
- void deleteEdge(int x, int y) {
- adjList[x].removeNeighbor(adjList[y]);
- }
- void dfsNonrecursive(int node) {
- boolean visited[] = new boolean[num_nodes];
- for (int i = 0; i < num_nodes; i++)
- visited[i] = false;
- visited[node] = true;
- System.out.println(node + ": " + adjList[0].getInfo());
- Stack<Integer> s = new Stack<Integer>();
- s.push(node);
- GraphNode<E> pom;
- while (!s.isEmpty()) {
- pom = adjList[s.peek()];
- GraphNode<E> tmp = null;
- for (int i = 0; i < pom.getNeighbors().size(); i++) {
- tmp = pom.getNeighbors().get(i);
- if (!visited[tmp.getIndex()])
- break;
- }
- if (tmp != null && !visited[tmp.getIndex()]) {
- visited[tmp.getIndex()] = true;
- System.out.println(tmp.getIndex() + ": " + tmp.getInfo());
- s.push(tmp.getIndex());
- } else
- s.pop();
- }
- }
- @Override
- public String toString() {
- String ret = new String();
- for (int i = 0; i < this.num_nodes; i++)
- ret += i + ": " + adjList[i] + "\n";
- return ret;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement