Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

5 Algorithms Graph

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Algorithms - Graph

What is Graph
- A tree which at least one cycle
V(G) = {1,2,3,4}
E(G) = {(1,2),(1,3),(3,3,),(3,4),(4,1)}

Graph Representation
- Adjacency Matrix representation
- Adjacency List
- Adjacency Multilist representation

Graph Representation

Graph Representation
- Adjacency Matrix representation

Graph Representation
- Adjacency List

Question ?
What graph topics should I study in order to be
adequately prepared for a Google Software Engineer
interview?
Depth-first Search, Breadth-first Search, and Dijkstra's algorithm are obviously required.
Would it be worthwhile to also study algorithms for minimum spanning trees, maximum network flows, bipartite matching, coloring
algorithms, topological sorting, etc...? How good should I be at implementing these algorithms from scratch?

Answer by Gayle Laakmann McDowell, Ex-Googler, Author of


Cracking the Coding Interview
I have never seen anything about Dijkstra's algorithm asked. It'd be a pretty stupid question.
First, very few interviewers would know it. It's not like they go home every night and re-read CLRS or whatever their algorithm
book is.
Second, it'd be way too hard. For candidates who were interviewing with me and finished a difficult question with some time to
spare (that is, doing very well), I would ask them how to delete a node from a binary search tree. Only about 20% of candidates
remembered this -- and this is of the really good ones. You think they know Dijkstra's algorithm?
Third, it wouldn't show anything. Knowing an algorithm says that you have a good memory or that you studied some stuff. We
don't care about that stuff. We care about your ability to solve *new* problems.
The same goes for all these other fancy algorithm problems. Seriously, this is not what tech interviews are all about. The actual
knowledge required is really just basic CS knowledge.
But here's what you should do: ignore my advice. Go look at actual google
interviews on CareerCup and Glassdoor. Go make your own decision about how important it is to know fancy algorithms. (Do not
look at blogs on interview questions. Best case, they have a huge selection bias and are intentionally picking the ridiculous
questions. Worst case, and more likely, they're lying or pulling their info from someone who lied.)
There's a reason I don't cover advanced graph algorithms in Cracking the Coding Interview: this stuff doesn't make it into
interviews.
The idea that Google asks such things largely comes from an incorrect assumption that a highly selective company must require
advanced knowledge. No, not exactly. They just set higher standards about your ability to solve new problems with basic CS
knowledge.

Disclaimer
The previous suggestion is the view of the specific
person.
Use your own judgement on what to study.
You are responsible for your career.
If extra knowledge does not confuse you, it does not
harm.

Depth First Search


void search(Node root) {
if (root == null) return;
visit(root);
root.visited = true;
foreach (Node n in root.adjacent) {
if (n.visited == false) {
search(n);
}
}
}
Please copy on your notebook

Explanation

visit(root);

Do processing needed
root.visited = true;

Processing is done
if (n.visited == false) {

Lets not process the same again


Not useful in tree as such but in a graph

What DS is used in DFS


Implicitly a stack , because we are using
recursion.

Breadth First Search


1: void search(Node root) {
2: Queue queue = new Queue();
5: queue.enqueue(root); // Add to end of queue
6:
7: while (!queue.isEmpty()) {
8:
Node r = queue.dequeue(); // Remove from front of queue
9:
visit(r);
10:
r.visited = true;
11:
foreach (Node n in r.adjacent) {
12:
if (n.visited == false) {
13:
queue.enqueue(n);
14:
}
15:
}
16: }
17:}
Please note in your copy.

Example

BFS Explanation
When we pick a node we insert all the
children at the rear end of the queue.

Lets run the BFS on previous tree and


see how the queue gets changed.

Activity
What will be the
DFS order ?
What will be the
BFS order ?

Three jug problem


I have three jug whose capacity are 8 lt.,5 lt. and 3 lt. and
no one jug is calibrated then how can I divide 8 lt. water in
two equal parts.

Can we write a program to solve this ?


Which algorithm will you choose
If there is no solution, can our program tell this.

Lets give it a manual try


Time : 3 minutes

Data Structures for Jug Problem


How can we store the state ?
We need a place to store whether this state is already
visited ?

Data Structures for Jug Problem


How can we store the state ?
Can we use a structure with three integers ?
We need a place to store whether this state is already
visited ?
Can we use a three dimensional array for this ?

Operations
What are the possible operations we can do on the states
of the water jug ?

Operations
What are the possible operations we can do on the states
of the water jug ?
When we pour from one jug to another
Either we fill the other jug to its capacity
Or we empty to first jug of whatever it had

Application of BFS and DFS


BFS : Whenever you need to search the minimal
number of steps.
DFS : When it is necessary to go till the leaf node, or
when we cannot maintain an additional data structure
such as queue.

Problem 1
1. Implement a function to check if a binary tree is
balanced. For the purposes of this question, a balanced
tree is defined to be a tree such that the heights of the
two subtrees of any node never differ by more than one.

Hint to Problem 1
During DFS on each node get the height and also check if
each sub left tree and right tree is balanced. If any sub tree
is not return -1 to indicate that a subtree is not balanced.

Problem 2
On a chessboard, a knight is placed at a random position
and a rook is placed at another random position. We need
to determine whether the knight can move over rook and
how many minimum steps will it take to reach there.

Hint to Problem 2
Use BFS
Use int[8][8] to mark the fact that the position is visited

Problem 3
3. Design an algorithm and write code to find the first common ancestor of two
nodes in a binary tree. Avoid storing additional nodes in a data structure.

Hint to Problem 3
A node is the LCA if
its left child reports it as /ancestor of one node
its right child reports it as /ancestor of other node
Or
If it itself is one node
the left or right child contains other node

Do a post order DFS and let every node determine whether it is a LCA node or
not. Pass to the parent as /ancestor information for both first node and second
node.

Problem 4
4. You are given a binary tree in which each node contains a value. Design an
algorithm to print all paths which sum to a given value. The path does not need
to start or end at the root or a leaf.

Hint to Problem 4
Do DFS and we pass the function the full path from root to
node & ask, "Does this node complete a path with the
sum?

Problem 5
5. Given a binary tree, design an algorithm which creates a linked list of all the
nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked
lists).

Hints to Problem 5
Use a linked list of linked lists to store the result
You can actually use either DFS or BFS for this purpose

Spanning Tree (Dijkstras method)

Spanning Tree (Dijkstras method)

Spanning Tree (Dijkstras method)

Spanning Tree (Dijkstras method)

Spanning Tree (Dijkstras method)

Spanning Tree (Dijkstras method)


tree=null;
edges=an unsorted sequence of all edges of graph;
for j=1 to IEI
add ej to tree;
If there is cycle in tree
Remove an edge with maximum weight from this only cycle.

You might also like