Saturday, August 9, 2014

Graph Depth-First traversal

Previous post (bfs), I covered BFS traversal. This post, I will be focusing on Depth-First traversal. 

The difference between BFS and DFS traversal lies in the order in which vertices are explored. And this mainly comes due to data structure used to do traversal. BFS uses queue whereas DFS uses stack data structure to perform traversal. Below diagram illustrates the order of traversal. 


DFS Progress

DFS Implementation

DFS implementation uses Graph.java from the post. Below class has two implementations of DFS traversals (recursive and iterative). Method, traverse(..) is stack based implementation whereas traverseRecur(..) is recursive implementation.

package graph.algo;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Depth-First Traversal of a graph represented as adjacency list
 * 
 * @author Siddheshwar
 * 
 */
public class DFS<V> {
 private Graph<V> graph; // graph on which DFS will be performed
 private Deque<V> stack; // Deque used to implement stack
 private Set<V> visited; // stores set of visited nodes

 public DFS(Graph<V> graph) {
  this.graph = graph;
  stack = new ArrayDeque<>();
  visited = new LinkedHashSet<>(); // to maintain the insertion order
 }

 /**
  * Iterative/stack based DFS implementation
  * 
  * @param source
  */
 public void traverse(V source) {
  Objects.requireNonNull(source, "source is manadatory!");
  if (this.graph == null || this.graph.isEmpty()) {
   throw new IllegalStateException(
     "Valid graph object is required !!!");
  }

  stack.push(source);
  this.markAsVisited(source);
  boolean pop = false;
  V stackTopVertex;
  System.out.print("  " + source);

  while (!stack.isEmpty()) {

   if (pop == true)
    stackTopVertex = stack.pop();
   else
    stackTopVertex = stack.peek();

   List<V> neighbors = graph.getAdjacentVertices(stackTopVertex);

   if (!neighbors.isEmpty()
     && hasUnvisitedNeighbor(neighbors, visited)) {
    for (V a : neighbors) {
     if (!this.isVertexVisited(a)) {
      System.out.print("  " + a);
      visited.add(a);
      stack.push(a);
      // break from loop if an unvisited neighbor is found
      break;
     }
    }
   } else {
    // if all neighbors are visited
    pop = true;
   }
  }
 }

 /**
  * Recursive implementation of DFS
  * 
  * @param source
  */
 public void traverseRecur(V source) {
  Objects.requireNonNull(source, "source is manadatory!");

  this.markAsVisited(source);
  System.out.print(" " + source);

  // get neighbors in sorted manner
  List<V> neighbors = this.graph.getAdjacentVertices(source);

  for (V n : neighbors) {
   if (!this.isVertexVisited(n)) {
    traverseRecur(n);
   }
  }
 }

 /**
  * checks if any of the neighbor is unvisited
  * 
  * @param neighbors
  * @param visited
  * @return
  */
 private boolean hasUnvisitedNeighbor(List<V> neighbors, Set<V> visited) {
  for (V i : neighbors) {
   if (!visited.contains(i))
    return true;
  }
  return false;
 }

 /**
  * Returns true if vertex is already visited
  * 
  * @param i
  * @return
  */
 private boolean isVertexVisited(V i) {
  return this.visited.contains(i);
 }

 /**
  * Mark a vertex visited
  * 
  * @param i
  */
 private void markAsVisited(V i) {
  this.visited.add(i);
 }

 // test method
 public static void main(String[] args) {
  Graph<Integer> graph = new Graph<>();
  graph.addEdge(1, 2);
  graph.addEdge(1, 5);
  graph.addEdge(1, 6);
  graph.addEdge(2, 3);
  graph.addEdge(2, 5);
  graph.addEdge(3, 4);
  graph.addEdge(5, 4);

  // for undirected graph
  graph.addEdge(2, 1);
  graph.addEdge(5, 1);
  graph.addEdge(6, 1);
  graph.addEdge(3, 2);
  graph.addEdge(5, 2);
  graph.addEdge(4, 3);
  graph.addEdge(4, 5);

  System.out.print("DFS -->");
  DFS<Integer> dfs = new DFS<>(graph);

  /**
   * stack based DFS traversal
   */
  dfs.traverse(1);

  /**
   * Recursive DFS traversal
   */
  // dfs.traverseRecur(1);

  // validation
  /**
   * after traversal; stack should be empty. And visited should have
   * vertices in DFS order
   */
  System.out.println("\nIs Stack is empty :"
    + (dfs.stack.isEmpty() ? "yes" : "no"));
  System.out.println("visited :" + dfs.visited);

 }

}

Output:
DFS -->  1  2  3  4  5  6
Is Stack is empty :yes
visited :[1, 2, 3, 4, 5, 6]



Time Complexity

Assuming above implementation of Graph i.e. Adjacency List, |V| is number of vertices and |E| is number of edges. 
So complexity is O(|V|+|E|)

--
happy learning !!!

Graph Breadth-First traversal

For doing anything meaningful with graphs; we should be able to traverse it in a certain order. Traversal helps in solving problems like searching for a vertex/edge, check if a path exists between two vertices, check if the graph is connected, check if the graph contains loop etc. 

There are two approaches for traversing a graph, BFS, and DFS. This post, I will be focusing on Breadth First Search (or traversal). It begins at a given root or origin node/vertex and visits all neighboring vertices. Then it starts visiting neighbors of its neighbors. This process is continued until all nodes are visited. It uses a queue to keep track of yet to be visited nodes. It also uses a separate data structure to mark all the visited nodes, this is required to make sure that the algorithm doesn't traverse the same node repetitively (if a loop exists).

In the above diagram, traversal starts at node 1. Afterwards, it visits its neighbors 2,5 and 6.

Breadth-First Search

Below diagram shows the order in which the nodes/vertices gets traversed in each step. It starts with vertex 1 and then finally ends at node 4. Below Java implementation use

BFS Traversal

Implementation

Below Java implementation uses Graph implementation from this Graph.java. 

package graph.algo;

import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;

/**
 * Depth-First Traversal of a graph represented as adjacency list
 * 
 * @author Siddheshwar
 * 
 */
public class BFS<V> {
 private Graph<V> graph; // graph on which dfs will be performed
 private Queue<V> queue;
 private Set<V> visited;

 public BFS(Graph<V> graph) {
  this.graph = graph;
  queue = new LinkedList<>();
  visited = new LinkedHashSet<>();  // to maintain the insertion order
 }

 /**
  * Return true if vertex is already visited
  * @param i
  * @return
  */
 private boolean isVertexVisited(V i) {
  return this.visited.contains(i);
 }

 /**
  * Add vertex to visited
  * @param i
  */
 private void markAsVisited(V i) {
  this.visited.add(i);
 }

 /**
  * Breadth-first traversal of the graph
  * 
  * @param source
  */
 public void traverse(V source) {
  Objects.requireNonNull(source, "source is manadatory!");
  if (this.graph == null || this.graph.isEmpty()) {
   throw new IllegalStateException(
     "Valid graph object is required !!!");
  }

  queue.add(source);
  System.out.print(" " + source);
  this.markAsVisited(source);

  while (!queue.isEmpty()) {
   V v = queue.remove();

   List<V> neighbors = graph.getAdjacentVertices(v);
   if (!neighbors.isEmpty()) {
    for (V n : neighbors) {
     if (!this.isVertexVisited(n)) {
      visited.add(n);
      System.out.print(" " + n);
      queue.add(n);
     }
    }
   }
  }
 }

 // test method
 public static void main(String[] args) {
  Graph<Integer> graph = new Graph<>();
  
  graph.addEdge(1, 2);
  graph.addEdge(1, 5);
  graph.addEdge(1, 6);
  graph.addEdge(2, 3);
  graph.addEdge(2, 5);
  graph.addEdge(3, 4);
  graph.addEdge(5, 4);

  graph.addEdge(2, 1);
  graph.addEdge(5, 1);
  graph.addEdge(6, 1);
  graph.addEdge(3, 2);
  graph.addEdge(5, 2);
  graph.addEdge(4, 3);
  graph.addEdge(4, 5);

  BFS<Integer> bfs = new BFS<>(graph);
  
  System.out.print("BFS -->");
  bfs.traverse(1);
  
  //validation
  /**
   * after traversal; queue should be empty. And visited should have
   * vertices in BFS order
   */
  System.out.println("\nIs Queue empty :"+ 
   (bfs.queue.isEmpty() ? " yes " : "no"));
  System.out.println("visited :" + bfs.visited);
 }

}

Output:
BFS --> 1 2 5 6 3 4
Is Queue empty : yes 

visited :[1, 2, 5, 6, 3, 4]

Time Complexity

Assuming above implementation of Graph i.e. Adjacency List, |V| is the number of vertices and |E| is number of edges. Each vertex is enqueued and dequeued at most once. Scanning for neighbors takes O(|E|) time. 
So complexity is O(|V|+|E|)
--
happy learning !!!

Thursday, July 31, 2014

Graph Implementation in Java

  1. In mathematics, and more specifically in graph threoy, a graph is a representation of set of objects where some pair of objects are connected by links - Wikipedia.
The graph is important for modeling any kind of relationship. So you can model road network between cities, the relationship among people (known as friendship graph) etc.

G = (V,E) 
A graph is defined as set of vertices V and set of edges (or vertex pair) E.


Let's take an example of flights between different cities, vertices represent cities and edges represent weight/cost of travel between a pair of cities. The graph can be directed if the edge(x,y) is not equivalent to the edge(y,x) otherwise it will undirected. Edges can also have the cost or weight associated with it.

Modelling the graph appropriately is quite important. Two basic data structures are - adjacency matrices and adjacency lists. Below is a weighted directed graph which represents the weighted cost of air travel between cities.


BL: Bangalore, HK: Hong Kong etc.



Adjacency Matrix represents G as an N x N matrix and matrix[i][j] = 1 if (i,j) is an edge of G, and 0 if it's not. If the graph is weighted then weight will be the value of the cell (assume that 0 means no connection). Adjacency List uses linked data structure to stores neighbors adjacent to each vertex.  If you are using adjacency list implementation to store undirected graph, the same edge (u,v) appears twice so that's extra space overhead. Each has its own pluses and minuses so which data structure you chose depends on what problem you going to solve. So think closely about the problem first before deciding the data structure. Practically adjacency list is right data structure for most of the applications.
But, the question like is (i,j) in graph? can be answered more easily if implementation is through Adjacency Matrix. 

Graph Implementation

Implementing the Adjacency Matrix is trivial, we just need a 2-dimensional array. This post, I will be implementing graph using adjacency list. Also, will be using two different approaches. 

Approach 1: The simplest possible adjacency list implementation could be a Graph class which has a collection of vertices and edges.


package graph.algo;

/**
 * Vertex represents points in a graph
 * 
 * @author Siddheshwar
 * @param <V>
 */
public class Vertex<V> {
 private V name;

 public Vertex(V name) {
  super();
  this.name = name;
 }

 public V getName() {
  return name;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((name == null) ? 0 : 
                         name.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Vertex other = (Vertex) obj;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  return true;
 }
}


package graph.algo;

/**
 * Represents connection between two vertices.
 * 
 * @author Siddheshwar
 * @param <V>
 */
public class Edge<V> {
 private Vertex<V> source;
 private Vertex<V> destination;
 int weight;

 public Edge(Vertex<V> source, Vertex<V> destination, int weight) {
  super();
  this.source = source;
  this.destination = destination;
  this.weight = weight;
 }

 public Vertex<V> getSource() {
  return source;
 }

 public Vertex<V> getDestination() {
  return destination;
 }

 public int getWeight() {
  return weight;
 }

 @Override
 public String toString() {
      return "Edge [source=" + source + ", destination=" + destination
    + ", weight=" + weight + "]";
 }
}


package graph.algo;

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

/**
 * Graph object as collection of vertices and edges
 * 
 * @author Siddheshwar
 * @param <V>
 */
public class GraphSimple<V> {
 private List<Vertex<V>> vertices;
 private List<Edge<V>> edges;

 public GraphSimple() {
  super();
  this.vertices = new ArrayList<>();
  this.edges = new ArrayList<>();
 }

 // other methods...
}


Approach 2: This approach uses the Map API of Java to create the relationship. The mapping between a vertex and node forms Edge. There is no explicit class to represent edges. So, source vertex is represented by vertex and the edge from source to target is represented by Node (by storing vertex as key and Node as value in map). The relationship or edge, in this case, gets represented by key-value in the map.

                     
package graph.algo;

/**
 * Node class to represent nodes in the graph. It will help in forming edges
 * 
 * @author Siddheshwar
 * 
 * @param <V>
 */
public class Node<V> {
 V name; // Vertex name
 int weight;

 public Node(V name, int weight) {
  super();
  this.name = name;
  this.weight = weight;
 }
 
 public V getName() {
  return name;
 }

 public int getWeight() {
  return weight;
 }

 @Override
 public String toString() {
  return "(" + this.weight + ")" + this.name;
 }
}


package graph.algo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Graph object which maps vertex with nodes
 * 
 * @author Siddheshwar
 * 
 * @param <V>
 */
public class Graph<V> {
 // Vertex i.e. V gets mapped to list of all connecting Nodes. 
 Map<V, List<Node<V>>> adjacencyList;
 int verticesCount;
 int edgeCount;

 public Graph() {
  super();
  this.adjacencyList = new HashMap<>();
 }

 /**
  * Add a new node for the given vertex. 
         *  Vertex to node connection forms Edge.
  * 
  * @param vertex
  * @param node
  */
 public void addNewNode(V vertex, Node<V> node) {
  List<Node<V>> nodes = adjacencyList.get(vertex);
  if (nodes == null || nodes.isEmpty()) { 
   nodes = new ArrayList<Node<V>>();
   nodes.add(node);
  } else {
   nodes.add(node);
  }
  adjacencyList.put(vertex, nodes);
 }

 /**
  * Takes two vertices and checks if there is a path between v1 and v2.
  * Doesn't take vice-versa.
  * 
  * @param v1
  *            first vertex
  * @param v2
  *            second vertex
  * @return
  */
 public boolean hasRelationship(V v1, V v2) {
  if (v1 == null && v2 == null)
   return true;
  if (v1 != null && v2 == null)
   return true;
  if (v1 == null && v2 != null)
   return false;

  List<Node<V>> nodes = null;

  if (adjacencyList.containsKey(v1)) {
   nodes = adjacencyList.get(v1);
   if (nodes != null || !nodes.isEmpty()) {
    for (Node<V> v : nodes) {
     if (v.getName().equals(v2))
      return true;
    }
   }
  }
  return false;
 }

 public void print() {
  System.out.println("Graph is --->");
  for (V v : adjacencyList.keySet()){
      System.out.println(v + " --- " + adjacencyList.get(v));
                }  
 }

 //Test method
 public static void main(String[] args) {
       Graph<String> graph = new Graph<String>();
       graph.addNewNode("Bangalore", new Node<String>("SFO", 100));
       graph.addNewNode("Bangalore", new Node<String>("HongKong", 50));
       graph.addNewNode("Bangalore", new Node<String>("LA", 70));
       graph.addNewNode("LA", new Node<String>("SFO", 20));
       graph.addNewNode("HongKong", new Node<String>("LA", 60));

       graph.print();

      System.out.println(" Path between Bangalore and LA exists ? :"
    + graph.hasRelationship("Bangalore", "LA"));
 }

}

Output:
Graph is --->
HongKong --- [(60)LA]
LA --- [(20)SFO]
Bangalore --- [(100)SFO, (50)HongKong, (70)LA]

 The path between Bangalore and LA exists? : true


This was a simplistic implementation of Graph, as I wanted to stress on fundamentals. This post has more refined Adjacency List graph implementation in Java. 


---
do post your feedback!!!

Saturday, June 28, 2014

Primitive data types of JavaScript

JavaScript is a loosely typed language so you can use a variable without declaring it. JavaScript determines the type based on the value contained in the variable.
JavaScript supports primitive data types along with objects. The simple/primitives types in JavaScript are number, string, boolean, null and undefiend. Everything except these are objects. Before starting on primitive data type; let's understand one of the important operator, typeof.

typeof operator : This operator returns data type of an argument as string.  This can be very helpful in determining the type. The return value of this operator for primitives could be - number, string, boolean or undefined. Apart from this everything else is of type object; so arrays are objects, functions are objects, and of course objects are objects.

Now, we are armed to start on data types in detail:

 Number

JavaScript uses number type to represent floating point numbers as well as integers. So 1 and 1.0 both are same value and of same type. It gets internally represented as 64-bit floating point (same as Java's double). This saves you from type errors because all you need to know about a number is that it is a number. It supports octal (starting with 0) and hex or hexadecimal number (starting with 0x) as well. Below screenshot shows some of the common operations on numbers.


String

In JavaScript, string is sequence of characters placed between either single quote or double quote. All characters are 16 bit wide. It doesn't support character type; so to represent character, make a string with just a single character. Strings in JavaScript are immutable; so once a string is created it can never be changed. It supports attributes and methods as well (just like normal objects).


Boolean

Boolean supports only two values true and false (without quotes). The operator typeof returns "boolean" if the value is either true or false. Boolean is also immutable and has methods just like numbers and strings. 

Undefined

When you declare a variable but don't initialize it then JavaScript will initialize it behind the scene for you with the value as undefined.

Null

Special data type which can have only one value i.e. null. It means no value. So if a variable has null value; it's still defined (contrary to undefined).


Monday, June 2, 2014

Wildcard in Generics

Generics is confusing (in fact one of the most confusing concepts of Java); and on top of it, wildcards (bounds) is even more confusing. That explains, the reason for this dedicated post :)
In the Generics post; I discussed that subtyping doesn't work with Generics. So, If Apple extends Fruit; list of Apple is not a subtype of list of Fruit. Does it mean that Generics can't be generic and you can't write a method which work for subtype? Luckily, wildcard helps you make Generics really generic.

Bounded Wildcard

Generics uses a wildcard character (?) to work with subtype. Let's go in detail on each.

upper-bounded wildcard: uses wildcard(?), followed by extends keyword, followed by its upper bound. 
List<? extends Number> will work for List of Number and list of its subtype (Integer, Double and Float).

List<Integer> li = new ArrayList<Integer>();
List<? extends Number> list = li;

lower-bounded wildcard: uses wildcard, followed by super keyword, followed by its lower bound. 
List<? super Integer> will work for list of Integer, list of Number and list of Object.

List<Number> ln = new ArrayList<Number>();
List<? super Integer> list1=ln;

Unbounded Wildcard

Using just the wildcard i.e. ? makes it unbounded. It means anything, so equivalent to using raw type. 
<?> says that; i wrote code keeping in mind Generics, but it can hold any type. 

List<?> is a non raw list of some specific type but we don't know what the type is. You can't pass any type. So the type is unknown but it doesn't mean that it can take any shit!

List<Integer> li2 = new ArrayList<Integer>();
List<?> l3 = li2;

 

Code Talk

Time to walk the talk through a simple example.

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

/**
 * Defines Base class Fruit and sub classes Apple and FujiApple. 
 * Uses BoundsGenericsTest for testing wildcard.
 * Save it as BoundsGenericsTest.java
 * 
 * @author Siddheshwar
 * 
 */
class Fruit {
 protected String name;

 public Fruit(String name) {
  super();
  this.name = name;
 }

 public String toString() {
  return name;
 }
}

class Apple extends Fruit {
 public Apple(String name) {
  super(name);
 }
}

class FujiApple extends Apple {
 public FujiApple(String name) {
  super(name);
 }
}

public class BoundsGenericsTest {
 List<? extends Fruit> list;

 public void add(List<? extends Fruit> f) {
  list = f;
 }

 public static void main(String[] args) {
  BoundsGenericsTest obj = new BoundsGenericsTest();

  List<Apple> apples = new ArrayList<Apple>();
  apples.add(new Apple("apple1"));
  apples.add(new Apple("apple2"));

  obj.add(apples);
  System.out.println(" list of Apples: " + obj.list);

  List<FujiApple> fujiApples = new ArrayList<FujiApple>();
  fujiApples.add(new FujiApple("fujiapple1"));
  fujiApples.add(new FujiApple("fujiapple2"));
  obj.add(fujiApples);
  System.out.println(" list of FujiApples : " + obj.list);

  List<? super FujiApple> another = 
                            (List<? super FujiApple>) obj.list;
  System.out.println(" val :" + another);
  List<? super FujiApple> another1 = fujiApples;
  System.out.println(" val :" + another);

  //unbounded wildcard
  List<?> fruits = apples;
  System.out.println("Fruits:" + fruits);
 }
}

Output:
 list of Apples: [apple1, apple2]
 list of FujiApples : [fujiapple1, fujiapple2]
 val :[fujiapple1, fujiapple2]
 val :[fujiapple1, fujiapple2]
Fruits:[apple1, apple2]

Related Post : Java Generics