36. Graphs-2 (traversal problems)

1. No. of provinces

Count total components in a graph, using any traversal technique
-----------------------------------------------------------------------------------------------------------------------------

2. Rotten oranges⭐

  Multi source BFS

time: O(n*m)   space: O(n*m)
--------------
- count all fresh at start and then count if these many will rot in the process or not

- here we do not need a visited matrix since we can modify given
- we update time each time there rots atleast one orange in a BFS cycle

---------------------------------------------------------------------------------------------------------------------------

3. No. of Islands

Count no. of islands (land surrounded by water in 4 directions)
----------------------------------------------------

time: O(n^2) space: O(n^2)

No. of islands = no. of graph components

-----------------------------------------------------------------------------------------------------------------------------

4. Flood Fill

BFS-
-----------------------------------------------------------------------------------------------------------------------------

5. No. of Enclaves

count no. of islands(group of 1s) where no land is on boundary

- set all 1s connected to boundary as 0, using multi source traversal

count remaining 1s (lands) in entire matrix
------------------------------
1. using BFS:
-----------------------------------
2. using DFS:
-----------------------------------------------------------------------------------------------------------------------------

6. No. of distinct islands



we need to store shape of islands in a set and then return st.count() 
In every dfs on an island, subtract base island coordinates from all neighbouring islands

-----------------------------------------------------------------------------------------------------------------------------

7. Surrounded regions

time: O(nm)        space: O(nm)

- simply do a multi source BFS, on boundary 0s and preserve these by replacing with #s
- now replace all inner 0s with Xs
- now replace #s again with 0s
-----------------------------------------------------------------------------------------------------------------------------

8. Dist of nearest cell having 0

we want to find distance of nearest 0s
so instead of doing BFS on every 1, 
we will use BFS on all 0s (multi source bfs)
jo koi bhi 0 kisi 1 ko pehle encounter krega toh us 1 ke liye vo wala 0 hi closest hoyega

---------------------------------------------------------------------------------------------------------------

Comments

Popular posts from this blog

30.) DP on subsequences

35. Graphs-1 (basics)