Skip to main content

Graphs - DFS

Its been a while I posted because I had been busy with other stuff.From now on i would be posting basically what I learn and how I implement it in my journey of preparing for the best interviews.

Now I am going to implement GRAPH DFS algorithm.
Graphs as we all know many people tend to fear as we implement but once you start realising the underlying beauty and power of the data-structure, you can not hold yourself implementing it.

Graphs can be represented as 2 ways: Adjacency lists or Adjacency matrices.

Here I use adjacency list because as i am using java it pretty easy to implement it using Collections framework.

DFS is pretty simple : Start with a node timestamp it and go deep and deep until u cannot go anywhere and then timestamp it. Finally you would end up creating a forest of multiple trees(Starting nodes).
Code below is self explanatory and if any one has any queries please let me know.
And the algorithm is direct implementation of book by Cormen (Introduction to Algorithms)




//Implementation of DFS on a directed graph

import java.util.ArrayList;
import java.util.HashMap;

//Class to represent each Vertex or node in a graph 
class Vertex {
int d;
int f;
String color;
Vertex predecessor;

Vertex() {
d = 0;
f = 0;
color = "white";
predecessor = null;
}
}

// Class to represent a graph [Vertex + Adjacency list]
class Graph {
ArrayList<Vertex> Vertices = new ArrayList<Vertex>(); // Array of Vertices
HashMap<Vertex, ArrayList<Vertex>> adjList = new HashMap<Vertex, ArrayList<Vertex>>(); // Adjacency
// list
static int time = 0;

// Initialize Vertices and adjacency list
Graph(int noOfVertex) {
for (int i = 0; i < noOfVertexi++) {
Vertices.add(new Vertex());
}
for (int j = 0; j < noOfVertexj++) {
adjList.put(Vertices.get(j), new ArrayList<Vertex>());
}

}

// Method to specify Nodes and adjacent nodes.
// Insert elements into adjacency list of a vertex
void insertInAdjList(int firstint second) {
adjList.get(Vertices.get(first)).add(Vertices.get(second));
}

// DFS Algorithm implementation
static void DFS(Graph g) {

for (Vertex u : g.Vertices) {
if (u.color.equals("white")) {
dfsVisit(gu);
}
}
}

// Helper method to visit a node and time-stamp it exploring depth wise
static private void dfsVisit(Graph g, Vertex u) {
time = time + 1;
u.d = time;
u.color = "grey";
for (Vertex v : g.adjList.get(u)) {
if (v.color.equals("white")) {
v.predecessor = u;
dfsVisit(gv);
}
}
u.color = "black";
time = time + 1;
u.f = time;
}
}

public class Graphmain {
public static void main(String args[]) {
Graph g = new Graph(6);

g.insertInAdjList(0, 1);
g.insertInAdjList(0, 4);
g.insertInAdjList(1, 4);
g.insertInAdjList(2, 4);
g.insertInAdjList(2, 5);
g.insertInAdjList(3, 1);
g.insertInAdjList(4, 3);
g.insertInAdjList(5, 5);
Graph.DFS(g);
for (Vertex u : g.Vertices)
System.out.println(u.d + " " + u.f);

}

}

Comments

Popular posts from this blog

Introduction to GIT and GITHUB

In this series I would be covering the basic operation of  GIT so that even a new comer can easily feel comfortable with the terminologies and usage of git system. The first post is just a brief introduction that will help you clarify the questions raising about this new thing. What is a Git? Git is simply a software that helps you manage your source code.That means each change that you make to a source code is recorded in its history.So it can also be called as Source Code managemnt system. To use git for a particular project all you need is to initialize the current project folder so that it will be tacked by the git system.I will show it in further documents about how to do it. Every Git working directory(or you can say your project folder) is a full-fledged repository with complete history and full version tracking capabilities, not dependent on network access or a central server. What is GitHub ? In layman terms you can think of

PyCache - A simple, yet extensible in memory Python caching library/framework

https://github.com/Abhisar/PyCache A Small library/extensible framework that aims to solve the problem of needing a cache while coding small/medium scale python projects without depending on 3rd party cache systems. PyCache This library aims to solve the problem of generic object(Python) caching without depending on 3rd party caching systems like Memcached or Redis for cases where it isn't really required. Library has been written in such a way it can be extensible by following standards through implementations of Python Abstract Base Classes. pycache folder  : It has all the base classes. One that ensures ensures all cache schemes follow a similar implemntation i.e https://github.com/Abhisar/PyCache/blob/master/pycache/BaseCache.py  and Other one is for the Objects to be cacheable they have to subclass this Base class  https://github.com/Abhisar/PyCache/blob/master/pycache/BaseCacheable.py CacheImplenations folder : This folder contains different caching schemes. Cur

Difference between spin locks and semaphores--Some Notes

up vote down vote accepted Both manage a limited resource. I'll first describe difference between binary semaphore (mutex) and spin lock. Spin locks  perform a busy wait - i.e. it keeps running loop(In turn heavy CPU usage example is in Reactor usage of AsyncTaskExecutors): while (try_acquire_resource ()); ... release(); It performs very lightweight locking/unlocking but if the locking thread will be preempted by other which will try to access the same resouce the second one will simply try to acquitre resource untill it run out of it CPU quanta. On the other hand  mutex  behave more like: if (!try_lock()) { add_to_waiting_queue (); wait(); } ... process *p = get_next_process_from_waiting_queue (); p->wakeUp (); Hence if the thread will try to acquire blocked resource it will be suspended till it will be avaible for it. Locking/unlocking is much more heavy but the waiting is 'free' and 'fair'. Semaphore  is a lock that is allowed to