


There is only one island and water surrounding it. There are no lakes, i.e., all the water is connected. Each edge of the land is 1 unit.
You are given map = [[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0]]
You are given the map as:

Here, it can be clearly seen the perimeter of the island is 12. Hence the answer is 12.
The first line of input contains a single integer ‘T’, representing the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, representing the number of rows and columns in the given map.
The following ‘N’ lines of each test case contain ‘M’ space-separated integers representing each row of the map.
For each test case print a single integer value representing the perimeter of the given island in the map.
Print the output of each test case in a separate line.
1 <= T <= 10
1 <= N, M <= 10^3
map[i][j] == 1 or 0
Time Limit: 1 sec
You do not need to print anything. It has already been taken care of. Just implement the function.
2
4 5
0 0 0 0 0
0 0 1 0 0
0 1 1 1 0
0 0 1 0 0
2 3
0 1 0
0 0 0
In this approach, we will iterate over the given ‘map’ matrix count the number of ‘1’. If any ‘1’ has a right or down neighbour land cell we count them separately. Since each ‘1’ can add a maximum of 4 towards the perimeter and if there exists a neighbour land cell we subtract 2 from the overall perimeter.
Hence the final perimeter is 4* number of ‘1’ - 2* no. of neighbours.