Saturday, March 12, 2022

Leet Code 463. Island Perimeter

Example 1:

Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16
Explanation: The perimeter is the 16 yellow stripes in the image above.








package pep.Day40;

public class Island_Perimeter {
public static void main(String[] args) {
int[][] grid = {{0, 1, 0, 0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}};

System.out.println(islandPerimeter(grid));
}

public static int islandPerimeter(int[][] grid) {
int boxes = 0, nbr = 0;
int[][] dirns = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};

for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
boxes++;
for (int[] dir : dirns) {
int x = dir[0] + i;
int y = dir[1] + j;

if ((x >= 0 && x < grid.length) && (y >= 0 && y < grid[0].length)) {
if (grid[x][y] == 1) {
nbr++;
}
}
}
}
}
}
return 4 * boxes - nbr;
}
}



No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...