Graphs Flashcards

1
Q

BFS

A

You visit all edges of a given node and only after visiting all the adj nodes, you visit their adjecent nodes. Level by level traversal.
To prevent repetitions we maintain visited array
Push s into q and mark it as visited.
While q is not empty
We pop and enqueue it’s children only if it is not already visited

For multi source bfs and for disconnected components we call bfs on every node if it is not already visited

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Number of connected components in a graph

A

Same as multi source bfs. We maintain a count variable whenever in the main function we call bfs in the for loop if the node is not already visited, we increase the count
Finally return the count

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Dfs

A

You visit a node and you recursively call DFS on each of its adjecent nodes. This results in completely processing the subgraph before moving to the next adjecent

DFS(s,adj[], visited[])
Mark s as visited
Print it
For every v in adj(u)
If not already visited
DFS(v,adj, vis)

Again to take care of disconnected components, we call DFS considering every vertex as source and if it is not already visited

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Shortest path in an undirected unweighted graph

A

Bfs traverses in shortest path possible.
Initialise distance vector to infinity
Dist(s) is 0
Push s into q and mark as visited
Now while q is not empty
Pop
For every adj v of u and not already visited
Dist(v)=dist(u)+1
Mark v as visited
Push v into q

Return dist

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Detect cycles in an undirected graph

A

We use DFS
Visited array alone is not sufficient to give info about cycles but needed anyway to prevent repetitions

We maintain a parent variable
If node is already visited and is parent then ok
If node is already visited and not parent then cycle is present

Dfsrec(adj, s visited parent)
Mark parent as visited
For every adj v of u
If not already visited then call DFS and see if it return true
If already visited and not equal to parent return true
After for loop then return false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Cycle detection in directed graph

A

The solution for undirected graphs will not work
We use DFS
In DFS recursion stack if there is a back edge then it means cycle is present.
To maintain rescursion stack we maintain bool recSt array

We pop from recSt only after all descendants are processed. This is what helps in disco components as well as 2 arraows ponting to same node cases
We still need visited array to account for disconnected components

Visited (s) as t
RecSt(s) as t
For every u in adj off s
If not already visited then call DFS and if it returns true return true
If already visited and recSt is true then back edge. So return true

RecSt(s) as false
Return false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Topological sorting

A

Khan’s algorithm
Push all nodes with indegree 0 into the q
Pop a node
Visit its adjecent nodes and decrease their indegree by 1
If indegree become 0 enqueue into q

When in degree is zero it means that it doesn’t depend on any other nodes so it can be done first

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Cycle detection in directed graph using Khan’s algorithm

A

If we processed all vertices then there is no cycle. There is a cycle means they are all dependent on each other and so in topological sorting some of them will not be processed
There won’t be any vertex with degree 0 at some point.
So in Khan’s algorithm we use a count variable to maintain the count of the nodes we processed
If count is equal to v then no cycle
Else cycle

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Topological sorting using dfs

A

Create an empty stack St
For every vertex u do the following
If u not visited call DFS
While stack is not empty pop and print

DFS(u,St)
Mark u as visited
For every adjecent v of u
If v is not visited call DFS(v,St)
Push u onto stack

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Shortest path in a weighted directed acyclic graph

A

The idea is to use topological sorting

Initialise distance vector to infinity
Dist(s) is 0
Find a topological sort of the graph
For every vertex u in topological sort
For every adj v of u
If distance of v >dist(u) + wt
Then update

We use topological sorting because when we are deciding the shortest distance for a given node, we need to know the shortest distances of previous nodes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Minimum spanning tree
Given a weighted connected and undirected graph

A

Prim’s algorithm
Greedy approach

Initialise key vector to infinity
And mset vector to false
Set key (0) as 0

For count =0 to v
Int u=-1
For i from 0 to v
If (meet(i) is false and key(i) < key of u) then u is i
Mset(u) as t
Res+= key(u)

Now traverse through all adjecents and update their keys
If graph(u,v) not 0 and !mest(v)
Key(v) is min(key(v) and graph(u,v)

Return res

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Dijkistra’s single source shortest path algorithm

A

Undirected and weighted

Initialise distance vector to infinity
Fin vector to false
Mark dist(s) as 0
Picking the minimum from nodes not finalized similar to prim’s

For count =0 to v
U=-1
For i from 0 to v
If fin(i) is false and dist(i) < dist(u) or u is -1
Then u=i
Mark fin(u) as t
Update weights if smaller
For v from 0 to v
If graph(u,v) not 0 and not finalized(v)
Dist(v) is min(dist(v), dist(u)+graph(u,v))

Return dist

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Kosaraju’s Algorithm to find strongly connected components

A

If a set of vertices are connected in such a way that every pair of vertices is reachable from the other, then this set is called a strongly connected component.

Why not use DFS or bfs ? They will work for undirected graphs but not for directed graphs. DFS will call all elements of starting from one node but not from the other
We will get strongly connected components using dfs if we start from sink elements.
Order the vertices in decreasing order of finish times in DFS
Reverse all edges
Do DFS for reversed graph in he order obtained in step 1. For every vertex print all reachable vertices as one strongly connected component.

Implementation of step 1
Create an empty stack St.
For every vertex u do the following
If u not visited
Defsrec(u,St)
While s is not empty pop an item and added to result.
Dfsrec(u,St)
Mark u as visited
For every adj v
If v is not visited
Dfsrec(v,St)
S.push(u)

Why do we need to reverse the graph? Strongly connected components remain strongly connected even when the graph is reversed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Bellman Ford algorithm

A

Shortest path from source to all vertices even with negative weight edges
We first find shortest paths that are one edge length away, then shortest paths that are 2 edge lengths away and so on…
We relax all edges v-1 times
For count =0, count d(u)+weight(u,v)
Update

For every edges uv
If d(v)> d(u) +weight(u,v)
Print negative edge cycle found

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Articulation points

A

Articulation points are the points removal of whose vertices and their associated edges increases the number of connected components to more than one.

If root of DFS tree has 2 children then it is an articulation point.
Discovery time - the order in which the nodes are discovered.
Low values- the lowest discovery time reachable from a given node.
If a non root node has a child whose low value is greater then discovery time of this node, then it is an articulation point.
I. E. If no ancestors are reachable from one of its children, the we say that it is an ap.
To take care of such vulnerable points or breaking points we often add edges.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Bridges

A

An edge which when removed increases the number of connected components of the graph
An edge uv is called a bridge if low value (v) > disc(u)

Back edges are never bridges

17
Q

Tarjans algorithm

A

Used to find strongly connected components

This stack is different from recursive stack as we do not remove a node once it is returned to its parent.
If all adjecents of a vertex u are done with recursive and disc(u) = low(u), then print this vertex and all other verices in the stack above the node

Back edge- when returned to its Ancestor
Cross edges- when returned not to its ancestor

Tarjans algorithm is better than kosaraju’s algorithm to find strongly connected components

18
Q

Kruskal’s algorithm

A
19
Q

All paths from source to target
Given a dag of n nodes labelled from 0 to n-1, find all possible paths from 0 to n-1 and return in any order

A

DFS
DFS(s,m, v, ans, graph)
v.push_back(s)
If s==dest
Then ans.push_back(v):
Return
For every adj u of s
DFS(u, m,v,ans,graph)

20
Q

Max area of an island

A

Global variable count and ans
For every disconnected component we initialise count to 0 and count the number of DFS calls or 1s present in that component.
Max area would be the max of all such counts
DFS(x,y,m,n,grid, visited)
Mark visited (x,y)=true
Count++
For every adj if not visited and if within the boundary, cal DFS
Ans=max(ans, count)

21
Q

Keys and rooms

A

No of disconnected components

22
Q

Find eventual safe states

A

A node will not be a safe state if it is stuck in any of the loops
There can be 3 cases
New node : we recursively call it’s adj nodes and if any one of them is unsafe we mark the current node as unsafe
If visited and is not safe,
Then we mark the current node also as unsafe
Detect cycle
If recSt(u) is true
Then mark both s and u as unsafe

DFS(s, graphs, visited, recSt, isSafe)
Visited(s) =true
RecSt(s)=true
For u in graph(s)
If visited (u)==false
DFS(u, ….)
If unsafe u then isSafe(s)=false
If already visited
If isSafe (u)== false then isSafe(s)=false
Cycle detection
If recSt(u)==true
IsSafe(u) and s is false

23
Q

Redundant connection

A

We use the concept of disjoint set union
DS(n+1);
Rank(n+1);
Initially every element is a seperate set
For i from 0 to n
DS(i)=i;
Rank(i) =1
For vec in edges
U=vec(0)
V=vec(1);
P1 = findparent(u)
P2
If same then return v
Else do union by rank
If (rank(P1)

24
Q

Find the number of closed islands
Given a binary matrix of 0s and 1s, find the number of closed islands. Closed islands are ones which are surrounded by 1 on all sides

A

Idea is to call DFS on boundry 0 as they cannot be closed islands. All components connected to boundry zeros are marked as -1 or not valid

Now we traverse through the matrix again and if we find a zero we do count++ and call DFS on that component. Basically we will have to count the number of of disco components
Void DFS(x, y, m,n, grid)
Mark grid(x,y)=-1
For all 4 adj
If safe and Val is 0
Call DFS on them

25
Q

Floyd warshall

A