Saturday, August 9, 2014

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

Sunday, June 1, 2014

TreeMap Implementation in Java

As the name suggests; TreeMap (i.e. TreeMap<K, V>) is a map implementation which is based on a binary search tree. It's an ordered map implementation where keys are comparable.  HashMap doesn't guarantee any order for keys, but TreeMap stores key in a sorted way. This allows you to use queries like find all keys lesser than a given value, find the smallest, largest etc. It sorts the keys in natural order i.e. considers them an instance of a Comparable interface (if Comparable is implemented). During creation, we can also provide an optional Comparator instance(discussed in detail, here). 

This post, I will be focusing mostly on the implementation aspect of TreeMap. It might be helpful to go through earlier post where I have talked about implementation of HashMap and LinkedHashMap.

Building Blocks

Let's cover major components of  TreeMap.

Red-Black Tree: TreeMap uses a Red-Black tree based NavigableMap implementation. A red-black tree is a self-balancing binary search tree; so most of the operations like search, get, put, remove take O(log n) time. This gets guaranteed by ensuring that after every insertion/deletion the upper bound on height is O(log n) i.e. tree is balanced. Red-Black tree colors every node as either red or black and follows certain rules to ensure that the tree remains balanced. Although AVL trees are more balanced compared to the Red-Black tree, Red-Black tree performs better if there are many frequent insertions and deletions.

The tree uses these two techniques for balancing :
  • Recoloring
  • Rotation 
The red-black tree first tries to re-color the node/s to balance the tree; if it doesn't work then it goes for rotation technique.


More details of this tree can be found, wikipedia.
I have discussed generic binary search tree implementation in Java, here.

Entry: Just like HashMap and LinkedHashMap; TreeMap also uses Entry node to store key, values pairs of each entry.

static final class Entry<K,V> implements Map.Entry<K,V>{
        K key;
        V value;         
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;  
        
       //other methods
}

Entry class represents the node of the tree. Along with key and value pairs, it stores references to the left and the right subtree as well. Also, unlike a normal Binary search tree, every node stores reference to its parent. This is required for rotating nodes to balance the tree. And as discussed above; it colors all nodes either red or black. Root node gets colored as black.

Note, one important difference in Entry class of TreeMap compared with HashMap and LinkedHashMap. TreeMap doesn't use hashing to perform operations. (i.e. Entry class doesn't have hash attribute)


Root: Stores the root node of the tree for traversal.
  private transient Entry<K,V> root;

Put Method: Put method is used to inserting key, value pair in the map. Insertion is similar to inserting a new node in the binary search tree. It uses Comparable or Comparator interface to compare key with the key of root node. And based on the returned value (-1, 0 or +1 ) it takes appropriate action. To get an idea of how it works; please go through this post. 
Another important thing worth mentioning is; after every insertion, TreeMap ensures that the tree is balanced, here.

Get Method: Get also works similar to the get of a binary search tree. Recursively traverses the tree until it finds the node. It traverses by using the binary search tree property (i.e. root.data > root.left.data and root.data < root. right.data).


Related Posts: HashMap Implementation, LinkedHashMap Implementation

--- 
happy learning!!!