This problem actually reduced to finding just the degree of a vertex and then calculating fence according to that

If have degree 0 then its a stand alone cell hence we need to cover every side i.e. 4 fences

If have degree 1 then it have one adjacent connected cell hence we need to cover 3 side i.e. 3 fences
and so on …
Implementation Tip
To calculate degree of the vertex we need to build an Adjacency List and this will take BigO of V^2 or You can sort that and use Binary Search but this going to be complicated because we need to sort this first according to row then according to column(for each row)
So, The Best solution which I thought to resolve this problem is to convert the row number and column number to just one big number. For this I multiplied row number with huge number(One more digit then the maximum range) and add the column number
Here is my Solution > https://www.codechef.com/viewsolution/23933567
Any suggestion, any improvement or any tips are welcome
Thank You