Java solution, counting horizontal && vertical lines


  • 1
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int rowLen = grid.length;
            int colLen = grid[0].length;
            
            int countV = 0;
            int countH = 0;
                    
            for (int i=0; i<=rowLen; ++i) {
                for (int j=0; j<=colLen; ++j) {
                    int left = (j>0 && i<rowLen) ? grid[i][j-1] : 0;
                    int top  = (i>0 && j<colLen) ? grid[i-1][j] : 0;
                    
                    int cur = (i<rowLen && j<colLen ) ? grid[i][j] : 0;
                    
                    if (left != cur) countV++;
                    if (top  != cur) countH++;
                }
            }
            
            return countV + countH;
        }
    }
    

Log in to reply
 

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