MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / islandPerimeter

Method islandPerimeter

java/0463-island-perimeter.java:6–32  ·  view source on GitHub ↗
(int[][] _grid)

Source from the content-addressed store, hash-verified

4 }
5
6 public int islandPerimeter(int[][] _grid) {
7 final int[][] grid = _grid;
8 final Set<Integer> visit = new HashSet<>();
9
10 final RecursiveBiFunction<Integer, Integer, Integer> dfs = new RecursiveBiFunction();
11 dfs.func = (i, j) -> {
12 if(i >= grid.length || j >= grid[0].length || i < 0 || j < 0 || grid[i][j] == 0)
13 return 1;
14 //convert 2D-Coordinate to 1D-Coordinate
15 int flatCoord = i*grid[0].length + j;
16 if(visit.contains(flatCoord))
17 return 0;
18
19 visit.add(flatCoord);
20 int perim = dfs.func.apply(i, j + 1);
21 perim += dfs.func.apply(i + 1, j);
22 perim += dfs.func.apply(i, j - 1);
23 perim += dfs.func.apply(i - 1, j);
24 return perim;
25 };
26
27 for(int i = 0; i < grid.length; i++)
28 for(int j = 0; j < grid[0].length; j++)
29 if(grid[i][j] != 0)
30 return dfs.func.apply(i, j);
31 return -1;
32 }
33}

Callers

nothing calls this directly

Calls 2

containsMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected