Just for fun. Traversal two times


  • 0
    public int islandPerimeter2(int[][] grid) {
        int m = grid.length;
        int n = m != 0 ? grid[0].length : 0;
        int perim = 0;
    
        for (int i = 0; i < m; i++) {
            perim += grid[i][0] ^ 0;
            for (int j = 1; j < n; j++)
                perim += grid[i][j] ^ grid[i][j - 1];
            perim += grid[i][n - 1] ^ 0;
        }
    
        for (int j = 0; j < n; j++) {
            perim += grid[0][j] ^ 0;
            for (int i = 1; i < m; i++)
                perim += grid[i][j] ^ grid[i - 1][j];
            perim += grid[m - 1][j] ^ 0;
        }
        return perim;
    }
    

Log in to reply
 

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