I think there’s another way to look at the question , I’ve traversed the matrix blocks (of two unique numbers) only once , I don’t really know bfs or dfs so here’s a simple approach .
Here’s my solution link.
Example, in a matrix
1 2 3
2 4 5
The traversal is like :
1-2
|
2
2-3
2
|
4
3
|
5
2-4
4-5
There’s only repeated traversal of those which form more then one block.
For single number blocks I’ve defined a simple separate function.
P.S. - It’s my first post so please excuse if my approach is not clear to you guys.