Graph

You might also like

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

Graphs

m a nu

(Part-2)
ma

- By Kapil Yadav

1. BFS/DFS Traversal
Problems
2.Cycle Detection In
Undirected and Directed
Graph

https://www.linkedin.com/in/kapilyadav22/
Basic Traversal Questions:
Number of provinces
Flood fill
Number of islands
Max Area of island
Number of closed islands
Count Sub Islands
Number of Enclaves
Rotting Oranges
All Paths from source to target
Keys and Rooms
Surrounded Regions
https://leetcode.com/problems/clone-graph/
https://www.geeksforgeeks.org/detect-cycle-undirected-graph/
Find Eventual safe state
01 Matrix
Pacific Atlantic Water Flow
Shortest path with alternating colors
Reorder Routes to Make All Paths Lead to the City Zero
Shortest Path visiting all nodes
Shortest Bridge
As Far from Land as Possible
Jump Game 3

https://www.linkedin.com/in/kapilyadav22/
-> We need find the
of
No. Provinces, or we can
say
the number

of connected
components.

#o
examplei-
I 2 ⑤

&

y 3

In
->
the above
example, there are two components, 1-4) and (5-7)
If BFS/DFS graph, find the no. of connected
->

we un on we can

components.
-> Lets
say
we run a DFS on the
graph, starting from I,

from 1 - 2 -3 -
4, so to
keep track of traversed nodes,
we need visited
array
a

Now from 4, there no to reach nest


of the unvisited nodes
->

way
is

C so
15,6,7, need to check node and call DFs
for
every
we

unvisited nodes.
-> The number of times DFS will be called from find circleNum
https://www.linkedin.com/in/kapilyadav22/
function be
will the No.
of provinces.
create
We can either
Adjacency
List
from given quid or can use
->

that
grid as
Adjacency
Matrix.

-> We will use the


given gridas adjmatrix.
since, need to count
the number of provinces, numbering of
->

we

nodes does not matter.


-> We will start
numbering from 0 to N-I, since will be
it
easy
for adjmatrixindices.

Algorithmin
Declare visited
a
array
and initialize it with 0.
->

Declare count variable and initialize it


with 0.
->

Run loop from 0 to


v-, where vis the No. nodes.
->

of
a

check if the Node visited or not.


->

is

↳ if not, then increment the count and win DFS.

https://www.linkedin.com/in/kapilyadav22/
7

Tc 0(u v)
=
+

sc 0(v)
=
+ 0(u)
↳ visited ↳ recursive stack space

this solved also,


list where TC:-0(v) +0 (v +2E)
usingAdj
->
can be

https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
form of and column.
have
given the
point
starting in the
->
We now

We need
change the
to colour
of starting point and its
->

conn

colour
ected
neighbours having some as
starting point
to new color.

#
example:-tpoint

d
110 6 8 8
- -
1

1

2
I

I · %I I o I

new color =2


12
I -


4
o
--
8-2 I

o
one
I

I I I

o I o I o I

-2 1
2 2 I
42 - 2 2 -


-

2 2 o 2
2 2 o 2 o

--
I - 0 I 2 o I 2 o I

2 2 2

2 2 o

2 o I

UTPUT

https://www.linkedin.com/in/kapilyadav22/
dfs (1,1)

->already
dfs (0,1) dfs(1,0) visited

dfs (0,0) dfs(1,1)

dfs(1,0)

dfs(2,0)

OR

dfs(1,1)
visited
taleedy
dfs(1,0) dfs(0,1)

dfs(0,0) dfs(2,0)

dfs(0,1)

dfs(0,2)
NOTE: point
If the
starting color is new color,
-

same as we

don't need to do
anything.
Given
grid will
be our final answer.

Example 2
input.
in

In
->

WC,we need to traverse


every node, which will
take o(WXM) time.

for four neighbours, (NXM 4)


and at mode,
traversing O +
every are
we so

TC 0(NXM)
=
+ 0 (NXMX4)
I
of
↳for
every ofcall, calling its I
neighbours
calling [so, in total will
be
4xNxM times
neighbours
called]
O(N M)
=
X

SC: O(NXM) + O(N M) +

↳ Recursive stack space - visited


array

There
->

a
is better
way
to call multiple recursive functions
on a
grid.
Y Directions, then take
If want
to
go
->

we

[4] 5 -1,0, 1,03


now
=

col[4] 90, +,0,13


=

https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
Flood Fill BFS:
using
-

BFS also check and


approach works in some its
way,next just
updates neighbours first, then
go
to level i.e
neighbours
of neighbours.

https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
->
we need to count the number
of islands.
->
We can use BFSIDFS is traverse
through the
grid.
Lets use BFS first.
->

need start
starting mode the
traveling
We to in
a
put so
->

queue,
from now=0,c01 =
0
index, and push the now & column index, where we
get
our land.
first
In
->
above
ex, (0,0)
=
I,s0 push (0,0) the
in
queue
and insert all the

value =l
neighbours having
We either take for
another matrix visited make
changes our
->
can or in

input matrix
only.
https://www.linkedin.com/in/kapilyadav22/
traverse element and
the matrix
We will
throughlandevery
->

in

check whether there is a or not.

No. of islands will


be
equal to the number times BES
of
->

called
traversing
while the nodes.
x

⑪!,:
i
o

! ii o o

1 I o I o

I o o I I o ..
I o

o o o o o oo o
o o

Input Output =1

⑧-
! ! ·
o

o ↓ I

1 I o I o (1,0)
I I o o o (0,1)
o o o o o
(00)

0 -0- o

!
o


O o 1 o (1,1)
1 I o I o (0,2)
I I o o o (1,0)
o o o o o
-1)

⑧ o 0 o

⑧ o
1
! o
(2,0)

o
I o I o (I, 1)
I I o o o (0,2)
o o o o o
xy0)
o o 0- o
(,2)
0


o o I o
·
(0,3)
I
o o o o (2,0)
I I o o o
(1,1)
o
(0)
o o o o

o · · · o
(3,0)
·
0 ⑧ I o
(1,2)
o % o I o (0,3)

o I o o o
(0)
o o o o o
⑪1)
https://www.linkedin.com/in/kapilyadav22/
· o o o o

0 oo o o
2,3)
oo o I o (3,0)
0 I oo o ⑫2)
o o oo o
-,3)

o ⑥ ⑤ o o

o o o
o o

·o o I o (3,1)
050 o o o (1,3)
o o o o o
(3/)

o ⑥ ⑤ o o

o o o oo

↓ (2,3)
·o o ⑩ o
/
o
⑧ o o o ⑬ 1)
o o o o o 1/3)

TC 0(NXM)
=
+ 0 (NXMX4) BES
I ↳for
every dfst call, calling its I
neighbours
calling of will
[so, in total 4xNxM times
neighbours
be

called]
O(N M)
=
X

SC: O(NXM) O(NXMvisited


+

↳ Recursive stack
or
space
array
queue space (BFS)
https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
This
->

problem same
is as Number of island.We
just
need to the
count island and
size of each
compare
whether it maximum
is or not.

and will Number of


TC
space complexity be same as
->

island.

https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
S

&
I

https://www.linkedin.com/in/kapilyadav22/
given should water
It that, closed land be covered
by
-> is

from all the


four directions
(up, down, left and -)
night
1

170-
I

Let's start
observing the
pattern:
->
-

The boundary land of the


grid be
cannot close.
- >

↓ ↓
> ⑳ o o o

· I 1 o

o I 1 ⑧
-> ⑧ ⑧ .

Land connected land


boundary
->
The with the
close.
closed land
cannot to
be a
cannot
of
↓18.
I
1

7
I

↑ ↑
I

I
1 !
cannot be a closed land.

other
->

than above two conditions, land


rest be closed.
will

Basically,
->

we are
identifying open lands and convert
them
into water mark visited, that
or we can
simply them so

we don't consider them in closed island.

-> so
first check for boundaries
and run a dfslifs to
mark all its lands to visited.
neighbour
(Because they cannot be closed).

We need to check first now, last first


->

now,
column and last column.

Traverse check
Now the
grid again, and if there is
-

land. If BESIDFS and increase the


any any,
run a

count closed island.


of
BFS/DFS will land
neighbouring
mark all the as visited
Because it considered
will as I closed island.

closed
island.

10.
I 11


Tc 0(M) +0(N)
=
0
+

(NXMX4) BES
I ↳for
every dfst call, calling its I
neighbours
calling of will
[so, in total 4xNxM times
neighbours
be

called]
O(N M)
=
X

SC: OCNXM) O
+

(NAMG visited
↳ Recursive stack
or
space
array
queue space (BFS)
https://www.linkedin.com/in/kapilyadav22/

https://www.linkedin.com/in/kapilyadav22/
In this problem, need to find the stands Guide
->

we in

sub-islands of
are
gridd or not.

->
so we need to consider
every and in
guide, and
match them
gridl.
in

->
If the stand in
guide matchess with the island
grid,
in

then the island will


be consider as sub-island.

if matches
Even don't
it with
gridl, it
completely.
->
traverse
and marked visited, but
it itis sub-island of
a grid.
tanto
flag return, whether it sub-
->
We can use a is

island or not.

1 I o
1 I o
I
o o ! o
o o
1 ·

o ⑧ o o o

i
o I
⑧ ⑧
o o 1 I

o I · · L 1

⑧ o ⑥ o ⑧
⑧ . .

o ⑩ ⑧ o ⑥ ⑨ ⑤

grid) guide

https://www.linkedin.com/in/kapilyadav22/
NOTE:-gride is not sub-island of
guidl, because we need to
consider the
complete island in
guide, not
partially.
island mark
But traverse the
guide completely
in and

flag 0.
=

TC 0(NXM)
=
+ 0 (NXMX4) BES
I ↳for
every dfst call, calling its I
neighbours
calling of will
[so, in total 4xNxM times
neighbours
be

called]
O(N M)
=
X

SC: O(NXM) O
+
(NM
↓ visited
↳ Recursive stack
or
space
away
queue space (BFS)
https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
->
It similar
is as number of closed islands.
But
->
here I denotes to land and o denotes the water.

closed connected
We
->
need to
find the enclave, so
boundary
lands cannot be closed enclave.

Tc 0(M) +0(N)
=
0
+

(NXMX4) BES
I ↳for
every dfst call, calling its I
neighbours
calling of will
[so, in total 4xNxM times
neighbours
be

called]
O(N M)
=
X

SC: O(NXM) O
+
(NM
↓ visited
↳ Recursive stack
or
space
away
queue space (BFS)

https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/

https://www.linkedin.com/in/kapilyadav22/
>
We have the
given fresh oranges, rotten
oranges
and cell.
empty
Rotten
oranges
not the
adjacent
fresh oranges
->

every
minute.
single
NOTE-a)These
6)It
can be more than
all
one rotten
initially.
orangeare
is
possible that
not fresh oranges
rotten
reachable
by oranges. unreachable

2 11 2 1 I ·1

I I I 210
21

I
I ⑧ I D o ·

I I ② 7
2 I I 2

case a) b)

> In a, there 4 rotten which not


oranges,
case are can

all other in minute.


oranges
one

so after 1 minute, there be


will no
fresh orange left.
-> In case 6.), there are
multiple fresh oranges which are

unreachable rotten wethen-1.


from oranges, so

consider a) there
multiple rotten
again,
case
oranges,
are
->

and each rotten its


at
orange impacting neighbour orange
time.

-> Here time is the constraint, we need to do it in


minimum time.

of problems, when find


-
so in these need
types we to

cost
shortest
path, minimum minimum time, etc, just
think BFS.
about
try to

(where each
edge same).
weight is

Here
->

each more takes one


minute, so we should use

BFS.
-> Because we consider all rotten at level
oranges
can one

on time t = 0.
At
->
next level, t=1, further oranges
will be rotten and
so
on, until all the reachable fresh oranges will
be

rotten.

check, whetherone
At theend,traverseagainthe gridto
->

Algorithm: 1. Take a to store now col no and time


queue no,
of rotten
stamp a
orange.
2. Push
until queue
all atten
does
oranges
in
queue
initially.
3. not
empty:
get -

->
Pop queue
check
->

fresh oranges neighbour in cells. (unvisted


I in
push the col
-> now no, no, queue
Mark
neighbours visited.
->

4. if any
Traverse
grid
to check
fresh orange
exists i

-
yes, return
if 1.
·

if
->

no, return max timestamp.

TC 0(NXM)
=
+ 0 (NXMX4)
I ↳for
every BFS call, calling its I
neighbours
calling BFS
[so, in total will
be
4xNxM times
neighbours
called]
O(N M)
=
X

SC: OCNXM) O
+

(NXMI, visited

queue space away
https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
->
We need to
find all
paths from source to destination.

1
o I

N v

2 >3

possible paths be
from 0 -> 1 - 3 and 0 -> 2 + 3.
->

can

->

need
we togo
to
depth until
we reach to
target, so
one

-> while
going
to
depth, add node
current to our current path,
while
coming back, remove current node to find other possible
paths.
[0] afx(0)

-
current
afsc)
Co,] dfs(z) [0,2] path

[0, 1,3]dfs (3) dfs(3)[0,2,3]

in
If our node
current
target
is
node, add current path
->

answer.

-> There can be 2N


atmax paths in DAG.

1
o I 0 -> 1 - 3

0 ->

1 - 2- 3

0- 2 - 3

0 - 3
N v

2 >3
To
exponential
=

=
O(2V), where N the number
is
nodes.
of

Sc= 0(2), to store all the


paths.
NOTE: -

In Actual, the total possible paths will


be less then
O(2V), but IN the
is
upper
limit.

https://www.linkedin.com/in/kapilyadav22/
visit
We will enter room o, from room o can rooms
->

we

whose these room


keys are in 0.

So, keep enteringallthethe rooms until we don't


get any key in
->

any
room or
keys are used.

15 enter
cannot
3-
ex -

2 0 - 3 we room 2.

0-3

so, to track entered rooms take visited


keep of array.
->

At
->

the end, traverse the visited array,


if all rooms are visited return that

else false.

https://www.linkedin.com/in/kapilyadav22/
TC O(N+E),
=

where N is number of rooms and


I number
is of keys.
Sc =
o (N) + 0 (N)


visited recursive stack space

We
->

can use BFS well.


as

https://www.linkedin.com/in/kapilyadav22/
->
It similar to Number closed islands and No.
is
of of
enclaves.

Here
->

we don't need to count the numbers, but we need to

replace surrounded with X.


region

https://www.linkedin.com/in/kapilyadav22/
->
start from boundary zeroes and mark them visited.
-> Traverse the matrix and all unvisited
again replace
10 with X.
We
->
can use BFSIDES to traverse the nodes.

Tc 0(M) +0(N)
=
0
+

(NXMX4) BES
I ↳for
every dfst call, calling its I
neighbours
calling of will
[so, in total 4xNxM times
neighbours
be

called]
O(N M)
=
X

SC: O(NXM) O
+
(NM
↓ visited
↳ Recursive stack
or
space
away
queue space (BFS)

https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
Given from need
having vertex to
a
graph 0 to v. We
->

have
find whether the
graph cycle or not.

be connected
NOTE: There can
multiple components.
We
->

can use
BFS/DFS to solve the
problem.
BFS.
Find
cycle
1.
using
the

The
->
idea is to traverse nodes BFS
in manner

and sinceit is undirected list


graph, so
Adjacency
contain
will some
edge two times, from AtB

and from BTA.

-> So we need to
keep record of parent
node.
need to
If
check
a node
previously
whether it
is

is
visited,
node
we

not.
parent or

If
->

a mode visited, but


is not a
parent of current
visited
mode, it means, the current node is
already
by other mode, so it
forms a
cycle.

https://www.linkedin.com/in/kapilyadav22/
EX - I 3

o 5

2 4

list
Adjacency of graph
0 21,23
-

1 -
20,33

2
-

20,43
3
-

21,53
4 -

52,57
S - >

[3,43
start of null, take it
-> with O, parent 0 is so as -1.

Algorithm in

v. (0 vel).
Take
- a visited
array size
of to

Take of pau (node, parent).


~
->

a
queue
push node and in it visited.
source
parent queue,mark
->

while does not


empty
->
queue
current node.
Traverse the
neighbours of
->

visited, push
If neighbours not it in
queue,
->

are

->

if visited and not


is
parent of current node,
contains
then it
cycle, return True,

Return does not contain


->

false, it
cycle.

-> denotes node


current
one
I denotes invisited neighbouring or
Parent=-1 I 3


5 ↑ ooooo
o
012345

(0, 1) -

2 4

I 3

5
o I 11 oo o
(2,0)
o I 234 5 (1,0)
2 4 (01)

I 3

5
o 1 1 1 1 o o
(3,1)

o
⑧ 1 2 3 Y 5

2 4

I 3

5
o I I I I I o (y,2)
o 7 2 3 Y S (3,1)
2 4 (2),0)

I 3

o 5
I 11 11 ↓ (5,3)
o I 2 -> Y S (Y,2)
2 4 ⑬1

visited
I 3 already
X
o 5

.,.yt
I I

- S (5,3)
2 4 (4)
Tc 0(u 2t)
= + + 0(v)

o(u)
sc
0(u)
=
+


quere visited
undirected
Detect
cycle in
graph using DFS: -

list
I 3 Adjacency of graph
0 - 21,23
5

=30,33
o

sqSs
4

-
2

dfs(0, -
1)

dfs(1,0) Afs(z,0)

dfs (3,1)

dfs(5,3)
X

dfs(Y,5)

/z,u)
xor6,2)
Tc
=

0(V) + O(u 2t)


+

Sc =
O(U) +
o(U)
↓ ↳ visited
recursive
stack space

https://www.linkedin.com/in/kapilyadav22/
DETECT A CYCLE IN A DIRECTED GRAPH
Given a Directed Graph with V vertices (0 to V-1), and E edges, check whether it contains any cycle or
not.


o I

3 2 3< 2

Ex -

1 Ex -

-> We have
already done
cycle
detection in undirected
graph using
DFS. But the same
algorithm will
not work here.

Let's understand
using ex-1.
->

dfs(0)

/D
/f)already cycle. visited, but
there is one

↓/r
dfs(3)

directed direction also matters, above


also will
graph,
-> In so

not work.

Consider ofs(0)
->

ex-2,


dfs(1)

ats(2) cycles
L
dfs(3)

dfs (0)

visited
so
->
on the same
path, if the node is
again, then
only
it contains directed
cycle in
graph.
visited find
Along with need pathvisited
->
to
array, we a array
whether visited node is current not
the on
path or
-

.
Ex-
o >s 4
>S

62
N v

3 12

visited ·00 0 0 0
| ⑩

① & 2345 ⑥

Pathwis
oo.oo o ·
(
① 123456

visited pathwis

dfs (0) 1000

01230123
1000

visited
I 100
pathvis
1 ⑧ · df,Xf,(,),,. visited

01230123
pathwis

visited,
not
but
one

01230123
already
f/ call,
Ifnot
visited pathwis path.
current
1() 1/ I
dfs(z)

L 230123

visited path vis


I 0. 10

·


dfs(y)
u56 4

/

11 Δ 1 1 ·
dfs(s)
Y 56456

/
21 / ( I 1dfs(6)
4 50456
already visited, present in path.
current

ofs
T X not call,
(y)
Tc 0(u t)
=
+

sc 0(2v).
=
Terminal out
nodes
having
nodes
degree
- =
0.
are

safe modes are modes, from path leads to terminal


every
->

node.
We done directed ofs above
have
cycle detection in
graph using
->

in

problem. We will
use the same in this problem.

mode.
Any node which a part of cycle will
never be safe
->

is a

which is connected will


also not safe
Any node to
cycle
->
a a

node.
7 1
>2

·
N

u < 3

https://www.linkedin.com/in/kapilyadav22/
1,2,3, contains but also connected
cycle,
-
7 with the
is
cycle.
$0, 0, 1,2,3,4 be
cannot safe node.

nodes, which doesn't contain


cycle
->
If we reach to the or
does not follow a
path containing
cycle, we can
say
that
node a
safe mode.

ex - 0 > 1 >3

u v v

22 y >5

2 and s are terminal nodes, there no


cycle in the
->
is

and either ends


graph every path is at
2 or 5.

0 -> 1 3 - 5

3
-

+ 5 terminal nodes.
reaching
-
4
1
paths
0 -

all
0 -
1 -
4 + 2

0 -
2

-> we need an
array
to store the saferodes after every
dfs call. We name it as ans

1 ⑥
I 1
ofs (0)

1
o o 11 11/ 1

D 012345
I 2 345

used ↑ 1-x
dfs(z) -> already called
to
U
store the o
I ⑧ I ⑧ 1 dfs(1)
D
statis 129345 1 -
of
safe
oo

0 ,23
·10
4s
1
dB(3) dfs(U)8.1 ns
nodes
↑/ +
dfs (5) dfs(e)
"dfs(s)
⑧ o ⑥ ⑧ D 0 1 1 1 0 1

D 12345 012345

ans[]
↓ already
called
safe node
Tc 0(V 1)
= +

Sc 0(yV)
=

https://www.linkedin.com/in/kapilyadav22/

&

If we
carefully observe, it's shortest distance
finding
->

cell.
problem, where we need to
find nearest of
from each

-> we need to find nearest O, so it become


easy, if we
find
nearest I
from O, because distance from 0 be 0.
to will

o's need
NOTE: -
There are
multiple in the
grid, so we to
consider all zeroes to calculate minimum distance.

https://www.linkedin.com/in/kapilyadav22/
The better it check
approachwill
->

be BFS, because will


level wise level. First
all zeroes with a distance, then
all I's distance, and
having
one so on.

Algorithm:1. Take a (m+n) distance array.


2. Take a
(mxu) visited
array.
and distance
Take
storing sowno, colino
3. a
queue
4. store all the entries
having o in the
queue. Mark them visited

while does not


empty:
5.
queue
-

-> current element


pop
dist
>
update assay.
unvisited,
check if the
neighbours are
->

if yes, push the sowno, col, no and distancet


i e & mark it visited.

o ·o ... o o ·

o I o .o. o o o

I 1 I o o o oo ⑧

Distance
Input visited
queue
(1,2,0
(1,0,0)
o o o I 2 I ①
⑧ ⑧
(0,2,0)
o 1 o I o
I o o ⑨
(0, 1,0)

1 1 1 o o ⑧ o ⑧ ⑧
(0,0,0)

Distance
Input visited
queue
(1,1,1)
o oo I 1 1 o o o (1,2,0)
(1,0,0)
· 1 o 7 I I ·
o
o (0,2,0)
(π0)
I o
1 1 o o o ⑨ o
((0,0)
Distance
Input visited
queue

o oo I I
I o o o (2,0
(1,2,0)
0 1
1 o 1 1 ② o

"
o

q I L I ② ⑧ oo ⑨

Distance
Input visited
queue
oo · 11 1 ⑧ ② o
(2,2,1)
(2,0,1)

I · I I I o ② (H,1,1)
I 1 I I I (/y)
Distance
Input visited
queue

o o · 11 1 o. o
(2,1,2)
(2,2,1)

I · I I I o p ② (2,0,1)
(H,1,1)
I 1 I I
I I · o ⑧ /
Distance
Input visited
queue

o o · 11 1 o. o
(2,1,2)

I · I I I o L ② (2,2,1)
I
I 1 I 19 I ↑ o I ↳,0,1
Distance
Input visited
queue

o o · 11 1 ⑧ ② o


I · I I I o I ②

I 1 I I ↑ I 1 2 I (1,2)
Distance
Input visited
queue

Tc 0(M + N)
= + 0 (M XNxy)

5c 0 =

(MXN) + 0 (MXN)
↓ ↓
distance visited
https://www.linkedin.com/in/kapilyadav22/

· I

-> pacific ocean

=0
connected
is

cells and
with
column
top
0
and
cells
left edges.
reachable
So, now are
=

from pacific ocean.

connected with

->-> pacific

j
ocean

https://www.linkedin.com/in/kapilyadav22/
connected and
Atlantic Ocean with
right down
edges,
->
is

so last now andlast column cells are reachable from atlantic


ocean.


& ->
reachable
from
ocean
atlantic

Now,
->
we need to
find the cells, from which water can flow
to both the oceans.

But
the condition is the water can
flow from higher
cell to lower cell.

for ex-

from 5, water can


flow in

↑ both the oceans.


Now the idea to find whether the water will flow from
->

is

particular cell or not


individually using
two-ed
grids.
-> One 2nd
grid required
is to store the answer of pacific
ocean and another 2nd
grid is
required to store the
answer of atlantic ocean.

Atlast traverse
will cell
and each of both
->

we
compare
the
grids, if water can flow from both the grids, we will
store the now no & column no in a 2d vector.

Now, How to
find whether water can
flow from
particular cell or not?

We can start
with the
edges cell, for pacific
->

ocean

start with first now & first column cells. Water can

flow from these cells.


water
-> Now, check whether the can flow from their
neighbour
cells or not.
& cell in
-> Take a
queue & store all the left top edges
and BFS
it start
traversing in manner.

all water
BAS will traverse for the cells from where
->

can come to current cell.

- We are
going from lower cell value to
upper all
value,means

Pacit"s↑

Atlantic Ocean

&

m
-p ·

Either cells value


from ocean to
having higher
->
we can
go
cells lower value.
or to ocean
by going through
idea
Our is to start from edge cells and reach to the cells
->

cell.
having value equal to or
greater then current

I 1 11 I o o o o
I
I 1 1 I ↓
I o · o 1
I ↓ 1 o ② I
o · I 1

f ↓ o ① I 1 ↓
o I I
I o ooo I I I 7 I

Water flow towards water


flow towards

pacific ocean atlantic ocean

12

· · o o
I
o o o 1 f

o ⑨ o ·
I

1 I · o ·

I · ·o o
https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
these red and flue
edges graph.
->

are on

and
be both red blue
edges graph.
-> There can on

-> We need to find the shortest distance from 0 to


every vertex,
alternate
but the condition the
is
edges color should be in

order, means either Red Blue Red Blue Red, or Blue


Red Blue Red Blue.

We
->

have given red and Blue


edges separate
in vectors.

list
-> We can create a combined
adjacency containing
edges from red and blue
edges array.
wait, combine
-> But if we Red & blue
edges array, then
how we will
identify, which one is connected to red
& connected Blue.
edge which one is to

https://www.linkedin.com/in/kapilyadav22/
-> We can store the
edges in a form of containing
pair
the vertex and its color, lets denote red as-1 and
Blue
edge as 1.

> so if a
edge from 01 red
is
edge, we can store
it like 0 ->
[1,-13

for alternate
Now
starting from O, BFS and check
->
wn

color, maintain a answer vector to stare shortest


path.

->
take visited size v. node be
a
array of One can

visited times, because there can be at


max vdifesent
paths like: -

o
->② here, O visit
will times.

-

ex-
X
I 12

13 u

Adjacency list

551, 1321, 1333, B


-

-
-

0
-

I -> [22,133
2 - 23
3 - 254,133
4 -
53
X INT

V
I 12

ans

INTENTINTENTin(0,0
a
O
e-I
13 u


I 12

ans (3, 1)

issaw
-

INT
· TAX INT INT INA the

O
o I 237

13 u

V3
I 12

(2,1) -> level -

3
ans
(3, 1)-

O o I INT INT INA (,1) level-2


237
-y
o I
13 u

X cannot consider 1-2

V
I 12
x
ans

o LINTINT INA (z,1) ->


Level-3

237
(3, 1)
O I

3
-

Level-2
13 u Lx)


I -2

ans

O 0 I INT I
INT
TAX (Y,1)
237
is
⑦ I
13 u
X

V
I 12

ans

O
o 1 2 I INT

Ms Brend-3

1237
13 u

V
I 12
ans

· 12 I 2

O
⑦ 123 Y

13 u (4,1) Level- 3
-

https://www.linkedin.com/in/kapilyadav22/
https://www.linkedin.com/in/kapilyadav22/
Since,
->
we need to
find minimum no of edge changes,
cones in mind
using
the BUS.
approach my
is

->
create
We can a Bidirectional
graph and the
edgeswhich are

from needs
going away
a to
change.

bidirectional
We take
will an
adjacency containing
list
graph.
->

To compare which
edges needs to
change, need
original graph
we
->

set.
edges, so store
original graph edges into a

start
traversing from node O, and if the
edges from
present
->

·to
neighbouring
its modes, we need to
change them, so count
them.

->
Basically, we are
originating BFS from O, so we
going away
from O, and if we are
getting edges, which are also
moving
need them.
away from, to
we severse

->
In
ex-1, 4-5
moving
is
away from O, so we need to
reverse it.
list
Adjacency
->
0 ->
[1,43
1 - 20,33
2- 233

3 - 26,23
->

4 - 15.03
5 -> [43
set:
Stove the
original graph edges in a
->
-

2(0,1,(1,3),(2,3),(,5),(Y,0)]
Take & pushe
a
queue
->

o
->
[0,13 present set,
in so need to
severse it
->

So,73 not
present in set, so no need
to reverse it. Y
① I

51,33 present
->
in set, so need to
reverse it

② 3
4
*

->
[4,53 present set,
in so need to
severse it

③ 5
3
M

E3,23
->

not
present in set, so no need 2

to reverse it. 5

all
neighbours visited.
3
->
Tc 0(u 2t)
=
+

https://www.linkedin.com/in/kapilyadav22/
There islands, both with water. need to
two
connecting
We
->

are are

find the minimum water cells to be severse to make them


island.
a
single
- The idea is to visit one of the island completely, mark
all the cells this island visited.
of
-> And
from island, visit
that the next island and the shortest

path to reach next island be


will the answer.

To stove all the cells island,


of use
queue.
->

an

-> And win a BFS from the calls


of first
queue, at level,
we need to
change O cells, at second level we need to

all
charge
1 and 0 on

https://www.linkedin.com/in/kapilyadav22/
I O ·1

I oo 1

101 I
(3,0)
(2, o
100 (1,0)
I (0,0)

->
Now run BFS and find nearest unvisited one (2nd island).

1 -0 ·1

I o 01

I ⑦ I I
(3,0)
(2, o
100 (1,0)
I
(0)

I O ·1

1-00 1 (17
(0,1)
L02

it ⑦ I I
(3,0)
I o o
I
Count=0

*,0)
3
(2, o
- level I

I O ·1

I o o 1 (2,1)
150 11
(1,1)
(0,1) 3 Level 2

It count =Δ (3,0)
(2, o 3 level/
o
01
/
I O ·1

I 001
(y)
I

I
4
⑦ I I
count=0 (1,1)
(0,1)
3 - level 2

-> 00 1
(5)

I 0 -0 1

I o o 1 2,2)
(3,1)

3
I ⑦ I I
count (z,D -
level 2

100 (1,1)
I
(0,1)

I O ·1

1 7,2)
I o
->
o

↓ 6,27
I ⑦ I I

10
01
Count=1
poiy - level 2

I O ·1

I o o 1
(1,2)
I ⑦ I I (0,2)
I
I o o

2
Court =
I

1

((,pz - w. 2

Level 2, count =1
Tc 0(M N)
=
+
+ 0 (M x Nx Y)
https://www.linkedin.com/in/kapilyadav22/
It
->
similar
is to 0 matrix.
We
->
will
use Multisource BFS.
value
We will store now, col, distance in
of cells
having
->

queue
1.

https://www.linkedin.com/in/kapilyadav22/
I · I I · I
oo o o
o o (2,2,0)
[ ①
7 10 7 (2,0,0)
visited (0,2,0)
(0,0,0)
1

D,0,
-
I I I I 1
· I
↓ o
o o I o o
(0, 1, 1
[ 0
I [ ①
7
(2,2,0)
visited (2,0,0)
(0,2,0)
(00)

D,2,1)
I ·t I I I I D,0, 1
↓ (0, 1, 1
o
o o
I o I
[ ①
7 [ · 7 (2,2,0)
visited (2,0,0)
10*,0)
I · I I I I
(z,1,1)
10 o o 1 o I 21,2,1)
1 0 7 [ I 7
D,0,
-

visited (0, 1, 1
(2,2,0)
(,0,0)

I · I I I I
o
(z,1,1)
o on 1 I
I
o
(1,2,1)
[ Ok I [ I 7
D,0, 1
visited (0, 1, 1
(4),0)

I I I I (1,1,2)
o
of I
(z,1,1)
o o 11 I
0
(1,2,1)
[ I [ I 7
D,0, 1 I
visited 10()
+c 0 =

( MXN) +
0 (UX MXN)
Sc 0 (MXN) + 0 (M X N)
=

https://www.linkedin.com/in/kapilyadav22/
solve recursion
We can this
problem using as well
->

as

BFS.
using
1)
Using recursion: -

Ex -

1: 9,4,2,3,0,3, 1,23
I start


*
O
Y ⑥
3X
-
-

12
x
① ⑦
y+
base
2
-

B
x

The

https://www.linkedin.com/in/kapilyadav22/
we aurlwindex), just mark
doing
=>
are to non-zerous

values index as visited.

TC = O(N)
Sc 0(N)
=
BFS:
Using
=

We
->
don't need to find all
teaching
paths with
index value 0.

find will
we
only need to one
path, so we
keep storing the
values
queue,
in until we reach till the
having
index 0.

-> 6423 >


1923 -> 4233 ->

4933 6223 1923


591} 5913
< 4333 6223

queue

- 3903 - 3903-> ↳3
4933 493
123

https://www.linkedin.com/in/kapilyadav22/
+c 0(N)
=

sc 0(N)
=
+0(N)

https://www.linkedin.com/in/kapilyadav22/
TRY YOURSELF
THANKYOU

4
=
-

1
https://www.linkedin.com/in/kapilyadav22/

You might also like