Simple java solution using XOR


  • 0
    A

    Scan matrix horizontally and vertically, if it is water-iland edge, count++, skip water-water edge and iland-iland edge.

    class Solution {
        public int islandPerimeter(int[][] grid) {
            int count=0;
            int row=grid.length;
            int col=grid[0].length;
            for(int i=0;i<row;i++){
                for(int j=0;j<=col;j++){
                    if(j==0){
                        count+=0^grid[i][j];
                    }
                    else if(j==col){
                        count+=grid[i][j-1]^0;
                    }
                    else{
                        count+=grid[i][j-1]^grid[i][j];
                    }
                }
            }
            
            for(int j=0;j<col;j++){
                for(int i=0;i<=row;i++){
                    if(i==0){
                        count+=0^grid[i][j];
                    }
                    else if(i==row){
                        count+=grid[i-1][j]^0;
                    }
                    else{
                        count+=grid[i-1][j]^grid[i][j];
                    }
                }
            }
            
            return count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.