Some fun with streams (Java 8 solution)


  • 0
    B

    Hi,

    Like almost everyone else, I compute 4 times the number of islands minus twice the number of links between islands. But to make it a bit more challenging, I decided to use Java 8 functional style. If you've never done it, give it a try. It's fun!

    Here's the code.

    public class Solution {
        public int islandPerimeter(int[][] grid) {
            return IntStream.range(0, grid.length)
                    .flatMap(row -> IntStream.range(0, grid[row].length)
                            .filter(col -> grid[row][col] != 0)
                            .map(col -> 4 - (col != 0 && grid[row][col - 1] != 0 ? 2 : 0)
                                          - (row != 0 && grid[row - 1][col] != 0 ? 2 : 0)))
                    .sum();
        }
    }
    

    I indented it for readability but it's basically a 1-liner. I love Java 8!


Log in to reply
 

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