Directed and Undirected Graph

This is small notes about graphs, There are two types of graphs, By just looking at below image you will understand the different of these two graphs.

In a directed graph direction matters. i.e. edge V2->V3 means that edge is directed. There is only an edge from V2 to V3 and no edge from V3 to V2. Therefore you can go from vertex V2 to vertex V3 but not from V3 to V2.

In undirected graph V2-V3 means the edge has no direction, i.e. V2-V3 means you can go both from V2 to V3 and V3 to V2.

1. Java Example Of Creating Undirected Graph :

public static Graph generateGraph() {

Graph graph = new Graph();

Node a = new Node("A");
Node b = new Node("B");
Node c = new Node("C");
Node d = new Node("D");
Node q = new Node("Q");
Node r = new Node("R");
Node g = new Node("G");
Node h = new Node("H");
Node i = new Node("I");
Node p = new Node("P");

return graph;

}

2. Java Example Of Creating Directed Graph :

public static Graph generateGraph() {

Graph graph = new Graph();

Node a = new Node("A");
Node b = new Node("B");
Node c = new Node("C");
Node d = new Node("D");
Node q = new Node("Q");
Node r = new Node("R");
Node g = new Node("G");
Node h = new Node("H");
Node i = new Node("I");
Node p = new Node("P");

return graph;

}

Some Utility Classes Used In Above Example :

State.java

package com.omt.learn.algo.util.graph;

public enum State {

VISITED, UNVISITED, FOUND
}

Node.java

package com.omt.learn.algo.util.graph;

import java.util.ArrayList;
import java.util.List;

public class Node {

private List<Node> adjacent = new ArrayList<>();
private String vertex = "";
private State state = State.UNVISITED;

public Node(String vertex) {
this.vertex = vertex;
}

}

public boolean isVisited() {
return getState() == State.VISITED;
}

return getState() == State.FOUND;
}

public State getState() {
return state;
}

public void setState(State state) {
this.state = state;
}

}

public String getVertex() {
return vertex;
}

}

Graph.java

package com.omt.learn.algo.util.graph;

import java.util.ArrayList;
import java.util.List;

public class Graph {

private List<Node> vertices = new ArrayList<>();