A stack is a data structure which only allows insertion and deletion from one end of the array. The insertion is always on the extreme end of the array. The deletion can only be done on the element which was most recently added.
<br/>
<b>It is similar to stacking plates.</b> The plate can only be added at the <b>top</b> of the stack and also only the last added plate to the stack can be removed (which will be on top).
<br/>
Due to this property, Last In elements are removed First from a stack. Therefore, it is called a <b>Last In First Out (LIFO)</b> data structure or a <b>First In Last Out (FILO)</b> data structure.
<br/>
To create a stack, we will keep track of the index which is the <b>top</b> of the array. This top index will <b>increment when we insert element</b> and <b>decrement when we remove element.</b>
Direct Address Tables are useful when we know that key is within a small range. Then, we can allocate an array such that each possible key gets an index and just add the values according to the keys.
assert(<spanstyle="font-weight: bold; text-decoration: underline;">false</span>&&<spanstyle="color: #50a14f;">"Key value out of boundry"</span>);
assert(<spanstyle="font-weight: bold; text-decoration: underline;">false</span>&&<spanstyle="color: #50a14f;">"Key value out of boundry"</span>);
assert(<spanstyle="font-weight: bold; text-decoration: underline;">false</span>&&<spanstyle="color: #50a14f;">"Key value out of boundry"</span>);
When the set of possible keys is large, it is impractical to allocate a table big enough for all keys. In order to fit all possible keys into a small table, rather than directly using keys as the index for our array, we wil first calculate a <i><b>hash</b></i> for it using a <i><b>hash function</b></i>. Since we are relying on hashes for this addressing in the table, we call it a hash table.
<br/>
<br/>
For a given key \(k_i\) in <b><i>direct address table</i></b>, we store value in \(table[k_i]\).
<br/>
<br/>
For a given key \(k_i\) in <b><i>hash table</i></b>, we store value in \(table[h(k_i)]\), where \(h()\) is the hash function.
<br/>
<br/>
So the main purpose of the hash function is to reduce the range of array indices.
Insertion can be done in \(\theta (1)\) time if we assume that key being inserted is not already in the linked list. But we can add a check to see if the key was already inserted and modify that value.
The <b>load factor</b> is defined as number of elements per slot and is calculated as
\[ \alpha \text{(Load factor)} = \frac{\text{number of elements in hash table}}{\text{number of slots in hash table}} \]
The worst case for chaining is when all keys are assigned to a single slot. In this case searching for an element takes \(\theta (n)\) time.
<br/>
<br/>
If we assume that any given element is equally likely to be hashed into any of the slots, this assumption is called <b><i>simple uniform hashing</i></b>.
<br/>
<br/>
If we also assume that hash funtion takes constant time, then in the average case, the time complexity for searching key in the chaining hash table is
\[ \text{Average Case Searching} : \theta (1 + \alpha) \]
In open addressing, all the key and value pair of entries are stored in the table itself. Because of this, the load factor \(\left( \alpha \right)\) can never exceed 1.
<br/>
<br/>
When we get a key whose slot is already taken, we will look for another empty slot. This is done by what is called <b><i>probing</i></b>. To get which slot to check next, we have various methods.
<br/>
<br/>
The sequence in which empty slots are looked for is fixed for given key, this sequence is called <b>probe sequence</b>. <br/>
It is necessary to keep probe sequence fixed for any given key, so that we can search for it later.
For a given <b>ordinary hash function</b> \(h(k)\), the linear probing uses the hash function
\[ linear\_h(k, i) = (h(k) + 1)\ mod\ m \]
We refer to \(h(k)\) as the <b><i>auxiliary hash function</i></b>.
<br/>
<br/>
In linear probing, we first check the slot [h(k)], if it is not empty, we check [h(k) + 1] then [h(k) + 2] …. upto slot [m - 1] after which we wrap around to [1], [2] … till we have checked all the slots.
<br/>
<br/>
Linear probing is easy to implement, but it suffers from <b><i>primary clustering</i></b>. In long runs of linear probing, keys tend to cluster together. This causes the performance of operations on hash table to degrade. The time to query a random element from table degrades to \(\theta (n)\).
Where, \(c_1\) and \(c_2\) are positive auxiliary constants.
</p>
<ulclass="org-ul">
<li>If m is not considered, we just assume \(c_1 = 0, c_2 = 1\), this is the simplest form of quadratic probing.</li>
<li>For \(m = 2^n\), a good choice for auxiliary constants is \(c_1=c_2=1/2\).</li>
<li>For \(m = n^p\) where m, n and p are positive integers greater or equal to 2, constants \(c_1 = 1, c_2 = n\) are a good choice.</li>
</ul>
<p>
Quadratic probing works much better than linear probing.
<br/>
<br/>
If \(quadratic\_h(k_1, 0) = quadratic\_h(k_2,0)\), then that implies that all \(quadratic\_h(k_1, i) = quadratic\_h(k_2,i)\), i.e, they will have the same <b>probe sequence</b>. This leads to a probe sequence getting clustered. This is called <i><b>secondary clustering</b></i>. This also effects performance but not as drastically as primary clustering.
\[ double\_h(k, i) = \left( h_1(k) + i \times h_2(k) \right) \ mod\ m \]
The value of \(h_2(k)\) must be <b>relatively prime (i.e, coprime) to number of slots (m)</b>. <br/>
</p>
<ulclass="org-ul">
<li>A convenient way to ensure this is let <b>m be a power of 2</b> and \(h_2(k)\) be a <b>hash function that always produces an odd number</b>.</li>
<li>Another way is to let <b>m be a prime</b> and make \(h_2(k)\) such that is <b>always produces a positive integer less than m.</b></li>
</ul>
<p>
If we use one of the above two methods (either m is a power of 2 or a prime), then double hashing improves over linear and quadratic probing since keys will have distinct probe sequences.
<br/>
<br/>
When using the above values of m, performance of double hashing is very close to the performance of "ideal" scheme of uniform hashing.
<b>*n</b> Performace of open addressing
In open addressing <b>load factor</b> \(\left( \alpha \right) \le 1\). We will assume <b>uniform hashing</b> i.e, any element is equally likely to be hashed in any slot. We will also assume that for any key, each possible probe sequence is equally likely.
<br/>
<br/>
Under these assumptions, for load factor \(\alpha\). The number of probes in an unsuccessful search is at most \(1/(1 - \alpha )\)
<br/>
This means that for a constant load factor, an unsuccessful search will run in \(\theta (1)\) time.
<br/>
<br/>
The number of probes on average for inserting an element under these assumptions is \(1/(1- \alpha )\)
<br/>
The number of probes on averge in a successful search is at most \(\frac{1}{\alpha} ln\left( \frac{1}{1-\alpha} \right)\)
A good hash funtion will approximately satisfy the <b>simple uniform hashing</b>, which means that any element is equally likely to be hashed to any slot.
</p>
<p>
\[ m : \text{Number of slots in hash table} \]
\[ n : \text{Number of elements in hash table} \]
</p>
<p>
Suppose we knew that our keys are from a set of real numbers and the keys are picked uniformly. In this case, we could simply use the hash function \(h(k) = floor(mk)\).
<br/>
<br/>
Similarly, in many cases we can make a reasonably good hash funtion if we know the distribution of keys.
<br/>
<br/>
We will look at a few ways to make a hash function.
In division method, we map a key \(k\) into one of the \(m\) slots by taking the remainder of k divided by m.
\[ h(k) = k\ mod\ m = k\ \%\ m \]
In most cases,
\[ m : \text{Number of slots in hash table} \]
But there are some cases where \(m\) is chosen to be something else.
</p>
<ulclass="org-ul">
<li>If \(m\) is a <b>power of 2</b>, then \(k\ mod\ m\) will give us the least significant \(log_2m\) bits of \(k\). When making a hash function, we want a function that depends on all bits of the key. So, <b><i>we should not use this method if m is a power of 2</i></b>.</li>
<li>A <b>prime number</b> not close to a power of 2 is a good choice for \(m\) in many cases. So when deciding the number of slots for the hash table, we can <i><b>try to make \(m\) a prime</b></i> which will accomodate our elements with less load factor.</li>
In multiplication method, we first multiply the key \(k\) with a constant \(A\) which is in range \(0 <A<1\).Thenwegetthe<b>fractional part</b> of \(kA\). Then we multiply the fractional part by \(m\) and floor it to get the hash.
\[ h(k) = floor(m \times decimal\_part(kA) ) \]
The advantage of multiplication method is that we can choose any value of \(m\). We can even choose \(m\) to be a power of 2.
<br/>
We can choose any value of \(A\). The value depends on characteristics of data,
When we know how many children any given node can have, i.e, the number of children is bounded. We can just use refrences or pointers to the nodes directly.
<br/>
For example, if we know we are making a binary tree, then we can just store refrence to left children and right childern.
When we don't know how many children any given node will have. Thus any node can have any number of children, we can't just use refrences. We could create an array of refrences to nodes, but some nodes will only have one or two childs and some may have no childs. This will lead to a lot of wasted memory.
<br/>
There is a way to represent such trees without wasting any memory. This is done by using <b>sibling refrences or pointers</b>.
The right sibling pointer will point to the right sibling of the node. This allows us to chain siblings and have unbounded number of siblings to the given node, therefore having unbounded number of children to any given parent. To make this approach easier to use, we can also add a pointer back to the parent node, though it is not compulsary.
A tree where any node can have only two child nodes is called a <b><i>binary tree</i></b>.
<br/>
A binary search tree is a tree where for any give node <b>the nodes stored in left sub-tree are less than the parent node</b> and the <b>nodes stored in right sub-tree are greater than the parent node</b> (or vice versa). So the left-subtree always have smaller elements and right sub-tree always have greater elements.
<br/>
<br/>
This property allows us easily search for elements from the data structure. We start our search at the root node. If the element we want is less than the current node, we will go to the left node ,else we will go to the right node. The concept is similar to the binary search on arrays.
Some common ways in which we usually query a BST are searching for a node, minimum & maximum node and successor & predecessor nodes. We will also look at how we can get the parent node for a given node, if we already store a parent pointer then that algorithm will be unnecessary.
We can search for a node very effectively with the help of binary search tree property. The search will return the node if it is found, else it will return NULL.
Finding the minimum and maximum is simple in a Binary Search Tree. The minimum element will be the leftmost node and maximum will be the rightmost node. We can get the minimum and maximum nodes by using these algorithms.
This algorithm will return the parent node. It uses a trailing node to get the parent. If the root node is given, then it will return NULL. <b>This algorithm makes the assumption that the node is in the tree</b>.
We often need to find the successor or predecessor of an element in a Binary Search Tree. The search for predecessor and succesor is divided in to two cases.
<b>Case 1</b> : If the node x has a right subtree, then the minimum of right subtree of x is the succesor.
<br/>
<b>Case 2</b> : If the node x has no right subtree, then successor may or may not exist. If it exists, the successor node will be the ancestor of x whose own left node is also the ancestor of x.
<b>Case 1</b> : If the node x has a left subtree, then the maximum of left subtree of x is the predecessor.
<br/>
<b>Case 2</b> : If the node x has no left subtree, then predecessor may or may not exist. If it exists, the predecessor node will be the ancestor of x whose own right node is also the ancestor of x.
When inserting and deleting nodes in BST, we need to make sure that the Binary Search Tree property continues to hold. Inserting node is easier in a binary search tree than deleting a node.
Deletion in Binary Search Trees is tricky because we need to delete nodes in a way that the property of the Binary Search Tree holds after the deletion of the node. So we first have to remove the node from the tree before we can free it.
We also use a helper function called Replace Child for deletion of node. This function will simply take parent node, old child node and new child node and replace old child with new child.
<spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">case 3 : two child and successor is right node of root node</span>
<spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">case 4 : two child and successor is not the right node of root node</span>
The performance of the search operation depends on the height of the tree. If the tree has \(n\) elements, the height of a binary tree can be between \(n\) and \(floor\left( 1+ log_2(n) \right)\).
<br/>
<br/>
To perform an operation on BST, we need to find the node where we have perform the operation. Since even in worst case <b>we only need to traverse the height of the search tree to search for any node</b>, the time taken to perform any operation on a Binary Search Tree is \(\theta (h)\) where, \(h\) is the height of the tree.
<br/>
<br/>
A binary tree with height of \(floor(1 + log_2(n))\) is called a <b>balanced binary tree</b>, otherwise it is an unbalanced tree. A balanced binary tree is the shortest height a binary tree with that number of nodes can have.
<br/>
<br/>
The worst case is when tree has a single branch, making the height of tree n. In this case, the worst case for any operation takes \(\theta (n)\) time.
<br/>
A balanced binary search tree in worst case for any operation will take \(\theta (log_2n)\) time.
There are three ways to traverse a binary tree, inorder tree walk, preorder tree walk and postorder tree walk. All three algorithm will take \(\theta (n)\) time to traverse the \(n\) nodes.
This algorithm is named so because it first traverses the left sub-tree recursively, then the node value and then traverses right sub-tree recursively.
This algorithm is called preorder algorithm because it will first traverse the current node, then recursively traverses the left sub-tree and then recursively traverse the right sub-tree.
<spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">recursively print left sub-tree</span>
preorder_print(node->left_child);
<spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">recursively print right sub-tree</span>
preorder_print(node->right_child);
}
</pre>
</div>
<ulclass="org-ul">
<li><b>This algorithm is used to create a copy of the Binary Search Tree</b>. If we store nodes in an array using this algorithm and then later insert the nodes linearly in a simple binary search tree, we will have an exact copy of the tree.</li>
<li>This algorithm traverses the tree in a <b>topologically sorted</b> order.</li>
<li>This algorithm cannot be used to delete or free the nodes of the tree.</li>
Heap is a data structure represented as a complete tree which follows the heap property. All levels in a heap tree are completely filled except possible the last one, which is filled from left to right.
<br/>
<br/>
The most common implementation of the heap is a <b>binary heap</b>. The binary heap is represented as a binary tree. We can use an array to implement binary heaps.
<br/>
<br/>
The heap data structure is used to implement <b>priority queues</b>. In many cases we even refer to heaps as priority queues and vice versa.
Also reffered to as <b>shape property</b> of heap.
<br/>
A heap is represented as a complete tree. A complete tree is one where all the levels are completely filled except possible the last. The last level if not completely filled is filled from left to right.
We can implement binary heap using arrays. The root of tree is the first element of the array. The next two elements are elements of second level of tree and children of the root node. Similary, the next four elements are elements of third level of tree and so on.
<br/>
<br/>
<i><b>For a given level, the position in array from left to right is the position of elements in tree from left to right.</b></i>
<br/>
<br/>
For example, a max-heap implemented using array can be represented as tree as shown
Both insertion and deletion in heap must be done in a way which conform to the heap property as well as shape property of heap. Before we can look at insertion and deletion, we need a way to find parent and child for a given index. We will also first see up-heapify and down-heapfiy funtions.
The down-heapify is a function which can re-heapify an array if no element of heap violates the heap property other than index and it's two children.
<br/>
This function runs in \(\theta (log_2n)\) time. The algorithm for this works as follows
</p>
<olclass="org-ol">
<li>Compare the index element with its children and stop if in correct order in relation to both children.</li>
<li>If not in correct order, swap the index element with the children which is not in correct order. Repeat till in correct order or at the lowest level.</li>
Since we shift element downwards, this operation is often called <i>down-heap</i> operation. It is also known as <i>trickle-down, swim-down, heapify-down, or cascade-down</i>
Since we shift element upwards, this operation is often called <i>up-heap</i> operation. It is also known as <i>trickle-up, swim-up, heapify-up, or cascade-up</i>
Insertion takes \(\theta (log_2n)\) time in a binary heap. To insert and element in heap, we will add it to the end of the heap and then apply up-heapify operation of the elment
<br/>
The code shows example of insertion in a max-heap.
Like insertion, extraction also takes \(\theta (log_2n)\) time. Extraction from heap will extract the root element of the heap. We can use the down-heapify function in order to re-heapify after extracting the root node.
Inserting an element and then extracting from the heap can be done more efficiently than simply calling these functions seperately as defined previously. If we call both funtions we define above, we have to do an up-heap operation followed by a down-heap. Instead, there is a way to do just a single down-heap.
<br/>
<br/>
The algorithm for this will work as follows in a max-heap.
</p>
<olclass="org-ol">
<li>Compare whether the item we are trying to push is greater than root of heap.</li>
<li>If item we are pushing is greater, return it.</li>
<li>Else,
<olclass="org-ol">
<li>Replace root element with new item</li>
<li>Apply down-heapify on the root of heap</li>
<li>Return the orignal root heap which we replaced.</li>
</ol></li>
</ol>
<p>
In python, this is implemented by the name of <b><i>heap replace</i></b>.
For a max-heap, deleting an arbitrary element is done as follows
</p>
<olclass="org-ol">
<li>Find the element to delete and get its index \(i\).</li>
<li>swap last element and the element at index \(i\), and decrease the size of heap.</li>
<li>apply down-heapify on index \(i\) if any of it's children violate the heap property else apply up-heapify if the parent element violates the heapify property.</li>
We can convert a normal array into a heap using the down-heapify operation in linear time \(\left( \theta (n) \right)\)
</p>
<divclass="org-src-container">
<preclass="src src-c"><spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">array.array[..] contains an array which is not a heap yet</span>
<spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">this funtion will turn it into a correct heap</span>
A graph is a data structure which consists of nodes/vertices, and edges. We sometimes write it as \(G=(V,E)\), where \(V\) is the set of vertices and \(E\) is the set of edges. When we are working on runtime of algorithms related to graphs, we represent runtime in two input sizes. \(|V|\) which we simply write as \(V\) is the number of vertices and similarly \(E\) is the number of edges.
We need a way to represent graphs in computers and to search a graph. Searching a graph means to systematically follow edges of graphs in order to reach vertices.
<br/>
<br/>
The two common ways of representing graphs are either using adjacency lists and adjacency matrix. Either can represent both directed and undirected graphs.
Every node in the graph is represented by a linked list. The list contains the nodes to which the list node is connected by an edge.
<br/>
Example, if list-0 contains node-3, then node-0 is connected to node-3 by an edge.
</p>
<ulclass="org-ul">
<li>For <b>undirected graphs</b> this will simply work by storing all nodes in list who have a shared edge with list node.</li>
<li>For <b>directed graphs</b> we will only add node to list, if edge goes from list node to the stored node.</li>
</ul>
<p>
So in our previous example, if list-0 contains node-3, then the edge goes from 0 to 3 in the directed graph.
<br/>
<br/>
The space taken by adjacency list representation is \(\theta (V + E)\).
<br/>
Since each node represents an edge, it is easy to convert an adjacency representation graph to a <b>weighted graph</b>. A weighted graph is a graph where each edge has an associated weight. So the weight of (u, v) edge can be stored in the node-v of u's list.
<br/>
The adjacency list representation is very robust and can represent various types of graph variants.
We use a single matrix to represent the graph. The size of the matrix is \(\left( |V| \times |V| \right)\). When we make the matrix, all it's elements are zero, i.e the matrix is zero initialized.
<br/>
<br/>
If there is an edge between vertices (x , y), we show it by setting
<li>For undirected graphs, to show edge (u , v) we have to set both matrix[u][v] and matrix[v][u] to 1.</li>
<li>For directed graphs, to show edge (u , v) which goes from u to v, we only set matrix[u][v] to 1.</li>
</ul>
<p>
The space taken by adjacency matrix is \(\theta (V^2)\).
<br/>
For undirected graphs, the matrix will be symmetrical along the diagonal, because matrix will be equal to it's own <b>transpose</b>. So we can save space by only storing half the matrix in memory.
<br/>
<br/>
When comparing asymptotic results, the adjacency list seems more efficient, but matrix has advantage of only storing 1 bit for each cell. So in denser graphs, the matrix may use less space.
<br/>
<br/>
We can store weighted graphs in adjacency matrix by storing the weights along with the edge information in matrix cells.
Many times we have to store attributes with either vertices or edges or sometimes both. How this is differs by language. In notation, we will write it using a dot (.)
<br/>
<br/>
For example, the attribute x of v will be denoted as v.x
<br/>
Similarly, the attribute x of edge (u , v) will be denoted as (u , v).x
For a quick approximation, when undirected graph and \(2|E|\) is close to \(|V|^2\), we say that graph is dense, else we say it is sparse.
<br/>
Similarly, for directed graph when \(|E|\) is close to \(|V|^2\), we can say graph is dense, else it is sparse.
<br/>
<br/>
The list representation provides a more compact way to represent graph when the graph is <b>sparse</b>. Whereas matrix representation is better for <b>dense</b> graphs.
<br/>
Another criteria is how algorithm will use the graph. If we want to traverse to neighbouring nodes, then list representation works well. If we want to quickly tell if there is an edge between two nodes, then matrix representation is better.
Graph search (or graph traversal) algorithms are used to explore a graph to find nodes and edges. Vertices not connected by edges are not explored by such algorithms. These algorithms start at a source vertex and traverse as much of the connected graph as possible.
<br/>
<br/>
Searching graphs algorithm can also be used on trees, because trees are also graphs.
BFS is one of the simplest algorithms for searching a graph and is used as an archetype for many other graph algorithms. This algorithm works well with the adjacency list representation.
<br/>
<br/>
In BFS, the nodes are explored based on their distance from the starting node. What we mean by distance between nodes is how many edges are in between the two nodes.
<br/>
<br/>
So in BFS, all nodes at distance 1 are explored first, then nodes at distance 2 are explored, then nodes at distance 3 and so on. That is, all nodes at distance \(k\) are explored before exploring nodes at distance \((k+1)\).
For an input graph \(G=(V,E)\), every node is enqued only once and hence, dequeued only once. The time taken to enqueue and dequeue a single node is \(\theta (1)\), then the time for \(|V|\) nodes is, \(\theta (V)\). Each node in adjacency list represents an edge, therefore the time taken to explore each node in adjacency lists is \(\theta (E)\). Therefore, the total time complexity is
For a simple graph, we may want to get the shortest path between two nodes. This can be done by making a Breadth-first tree.
<br/>
<br/>
When we are traversing nodes using BFS, we can create a breadth-first tree. To make this tree, we simply need to set parent of u in the inner while loop in the BFS algorithm to v. So our algorithm from earlier will become.
u.parent = v; <spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">the parent of u is v</span>
queue.add(u);
<spanstyle="color: #a626a4;">if</span>(u == end) <spanstyle="color: #a626a4;">return</span>; <spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">if we found the end node,</span>
<spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">we have the path to it.</span>
}
adjacency_list = adjacency_list.next;
}
}
printf(<spanstyle="color: #50a14f;">"end node not in graph"</span>);
}
</pre>
</div>
<p>
In this tree, the path upwards from any given node to start node will be the shortest path to the start node.
<br/>
Therefore, we can get the shortest path now as follows
Unlike BFS, depth first search is more biased towards the farthest nodes of a graph. It follows a single path till it reaches the end of a path. After that, it back tracks to the last open path and follows that one. This process is repeated till all nodes are covered.
Implementation of DFS is very similar to BFS with two differences. Rather than using a queue, we use a <b>stack</b>. In BFS, the explored nodes are added to the queue, but in DFS we will add unexplored nodes to the stack.
The difference between recursive and iterative version of DFS is that, recursive will choose the path of first neighbour in the adjacency list, whereas the iterative will choose the path of last neighbour in the adjacency list.
</p>
<ulclass="org-ul">
<li><b>Analysis</b></li>
</ul>
<p>
For an input graph \(G=(V,E)\), the time complexity for Depth first search is \(\theta (V + E)\), i.e, it is the same of breadth first search. The reasoning for this is the same as before, all nodes are pushed and popped from stack only once, giving use time complexity of \(\theta (V)\). We go through all the adjacency lists only once giving time complexity \(\theta (E)\). Thus adding the two will give us
\[ \text{Time complexity of DFS : } \theta (V + E) \]
DFS is very useful to <b><i>understand the structure of a graph</i></b>. To study the structure of a graph using DFS, we will get two attributes of each node using DFS. We suppose that each step in traversal takes a unit of time.
</p>
<ulclass="org-ul">
<li><b>Discovery time</b> : The time when we first discovered the node. We will set this at the time we push node to stack. We will denote it as node.d</li>
<li><b>Finishing time</b> : The time when we explored the node. We will set this when we pop the node and explore it. We will denote it as node.f</li>
</ul>
<p>
So our funtion will become
</p>
<divclass="org-src-container">
<preclass="src src-c"><spanstyle="color: #a0a1a7; font-weight: bold;">// </span><spanstyle="color: #a0a1a7;">call start node with time = NULL</span>
This algorithm will give all nodes the (node.d) and (node.f) attribute. <b>Similar to BFS, we can create a tree from DFS.</b> Having knowledge of these attributes can tell us properites of this DFS tree.
If \(y\) is a descendant of \(x\) in graph G, then at time \(t = x.d\), the path from \(u\) to \(v\) was undiscovered.
</p>
<p>
That is, all the nodes in path from \(x\) to \(y\) were undiscovered. Undiscovered nodes are shown by white vertices in visual representations of DFS, therfore this theorem was named white path theorem.
</p>
</div>
</li>
<li><aid="org44106c0"></a><b>Classification of edges</b><br/>
<divclass="outline-text-5"id="text-7-4-4-3">
<p>
We can arrange the connected nodes of a graph into the form of a Depth-first tree. When the graph is arranged in this way, the edges can be classified into four types
</p>
<olclass="org-ol">
<li>Tree edge : The edges of graph which become the edges of the depth-first tree.</li>
<li>Back edge : The edges of graph which point from a descendant node to an ancestor node of depth-first tree. They are called back edge because they point backwards to the root of the tree oppsite to all tree edges.</li>
<li>Forward edge : The edges of graph which point from a point from an ancestor node to a descendant node.</li>
<li>Cross edge : An edge of graph which points to two different nodes</li>
</ol>
<p>
The back edge, forward edge and cross edge are not a part of the depth-first tree but a part of the original graph.
</p>
<ulclass="org-ul">
<li>In an <b>undirected graph</b> G, every edge is either a <b>tree edge or a back edge</b>.</li>
<h4id="org5a44e62"><spanclass="section-number-4">7.4.5.</span> Depth-first and Breadth-first Forests</h4>
<divclass="outline-text-4"id="text-7-4-5">
<p>
In directed graphs, the depth-first and breadth-first algorithms <b>can't traverse to nodes which are not connected by a directed edge</b>. This can leave parts of graph not mapped by a single tree.
</p>
<p>
These tree's can help us better understand the graph and get properties of nodes, so we can't leave them when converting a graph to tree.
<br/>
To solve this, we have <i><b>collection of trees for the graph</b></i>. This collection of trees will cover all the nodes of the graph and is called a <b>forest</b>. The forest of graph \(G\) is represented by \(G_{\pi}\).
</p>
<p>
Thus when using DFS or BFS on a graph, we store this collection of trees i.e, forests so that we can get properties of all the nodes.
</p>
<ulclass="org-ul">
<li><b>NOTE</b> : When making a depth-first forest, we <b>don't reset the the time</b> when going from one tree to another. So if finishing time of for root of a tree is \(t\), the discovery time of root node of next tree will be \((t+1)\).</li>
<h4id="org1c39417"><spanclass="section-number-4">7.4.6.</span> Topological sort using DFS</h4>
<divclass="outline-text-4"id="text-7-4-6">
<p>
Topological sorting can only be done on <b>directed acyclic graphs</b>. A topological sort is a linear ordering of the nodes of a directed acyclic graph (dag). It is ordering the nodes such that all the <b>the edges point right</b>.
</p>
<p>
Topological sorting is used on <b>precedence graphs</b> to tell which node will have higher precedence.
</p>
<p>
To topologically sort, we first call DFS to calculate the the finishing time for all the nodes in graph and form a depth-first forest. Then, we can just sort the finishing times of the nodes in descending order.
</p>
<p>
TODO : Add image to show process of topological sorting
</p>
<ulclass="org-ul">
<li>A directed graph \(G\) is <b>acyclic if and only if</b> the depth-first forest has <b>no back edges</b>.</li>
If we can traverse from a node \(x\) to node \(y\) in a directed graph, we show it as \(x \rightsquigarrow y\).
</p>
<ulclass="org-ul">
<li>A pair of nodes \(x\) and \(y\) is called if \(x \rightsquigarrow y\) and \(y \rightsquigarrow x\)</li>
<li>A graph is said to be strongly connected if all pairs of nodes are strongly connected in the graph.</li>
<li>If a graph is not strongly connected, we can divide the graph into subgraphs made from neighbouring nodes which are strongly connected. These subgraphs are called <b>strongly connected componnents</b>.</li>
</ul>
<p>
Example, the dotted regions are the strongly connected components (SCC) of the graph.
We can find the strongly connected components of a graph \(G\) using DFS. The algorithm is called Kosaraju's algorithm.
</p>
<p>
For this algorithm, we also need the transpose of graph \(G\). The transpose of graph \(G\) is denoted by \(G^T\) and is the graph with the direction of all the edges flipped. So all edges from \(x\) to \(y\) in \(G\), will go from \(y\) to \(x\) in \(G^T\).
</p>
<p>
The algorithm uses the property that transpose of a graph will have the same SCC's as the original graph.
</p>
<p>
The algorithm works as follows
</p>
<ulclass="org-ul">
<li><b>Step 1</b> : Perform DFS on the tree to compute the finishing time of all vertices. When a node finishes, push it to a stack.</li>
<li><b>Step 2</b> : Find the transpose of the input graph. The transpose of graph is graph with same vertices, but the edges are flipped.</li>
<li><b>Step 3</b> : Pop a node from stack and apply DFS on it. All nodes that will be traversed by the DFS will be a part of an SCC. After the first SCC is found, begin popping nodes from stack till we get an undiscovered node. Then apply DFS on the undiscovered node to get the next SCC. Repeat this process till the stack is empty.</li>
</ul>
<p>
Example, consider the graph
</p>
<ulclass="org-ul">
<li>Step 1 : we start DFS at node \(1\), push nodes to a stack when they are finished</li>
<li>Step 2 : Find transpose of the graph</li>
<li>Step 3 : pop node from stack till we find a node which is undiscovered, then apply DFS to it. In our example, first node is \(1\)</li>