The distance between any two cells (x0, y0) and (x1, y1) is given by the Manhattan distance: |x0 - x1| + |y0 - y1|.
If no land or water exists in the grid, then return -1.
The first line of input contains an integer βT' representing the number of test cases.
The first line of each test case contains one integer βNβ denoting the size of the matrix.
The next βNβ lines contain βNβ integers separated by spaces describing rows of matrix βARRβ (each element of βARRβ is either 0 or 1).
For each test case, on a separate line, output one integer - the largest distance from a water cell to the nearest land cell.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N <= 10^3
ARR[i][j] = 0 or 1
Time limit: 1 sec
The idea here is to calculate the distance from each land cell and update every water cell to the minimum distance via any land cell.
We declare a 2d matrix minDistance[][] initially set to Infinity, and then run BFS from every land cell and calculate the shortest distance to each water cell, and update the minDistance[][] to the minimum shortest distance to a water cell. The maximum value which is not equal to infinity, of the water cell in minDistance[][] will be our ans.
The algorithm is as follows:
The idea here is to think in reverse order and imagine expanding outward from each land cell i.e. using BFS from all land cells at the same time.
If we put all the land cells in the queue and then we expand in all four directions and visit the water cell one level at a time. The maximum level reached will be our ans.
The algorithm is as follows:
Valid Arrangement of Pairs
Valid Arrangement of Pairs
Valid Arrangement of Pairs
Valid Arrangement of Pairs
Valid Arrangement of Pairs
Left Right Print
COUNT ISLANDS
The Summit
Distance to a Cycle in Undirected Graph