Last active
August 11, 2022 20:57
-
-
Save goteusz-maszyk/323b6188319353900ab54f0ff20c66b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IslandPerimeter { | |
public static void main(String[] args) { // for tests | |
int p = new IslandPerimeter().islandPerimeter(new int[][]{{0,1,0,0},{1,1,1,0},{0,1,0,0},{1,1,0,0}}); | |
System.out.println(p); | |
} | |
public int islandPerimeter(int[][] grid) { | |
int perimeter = 0; | |
for(int i = 0; i < grid.length; i++) { | |
int[] row = grid[i]; | |
for(int j = 0; j < row.length; j++) { | |
if(row[j] == 0) continue; | |
int toAdd = 4; | |
if(i != 0 && grid[i-1][j] == 1) toAdd -= 1; | |
if(i+1 != grid.length && grid[i+1][j] == 1) toAdd -= 1; | |
if(j != 0 && grid[i][j-1] == 1) toAdd -= 1; | |
if(j+1 != row.length && grid[i][j+1] == 1) toAdd -= 1; | |
perimeter += toAdd; | |
} | |
} | |
return perimeter; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment