Problème
The grid holds 1 for land and 0 for water. Each land cell is a 1×1 square. Compute the total perimeter of all land: every side of a land cell that faces water or the grid edge counts 1.
Implement island_perimeter(grid).
Input
grid: A rectangular grid of 0s and 1s.
Output
Return the total perimeter.
Contraintes
0 ≤ rows, columns ≤ 200
Exemples
Entrée :
grid = [
[0, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0]
]
Sortie attendue :
expected = 16
Entrée :
std::vector<std::vector<long long>> grid = {
{0, 1, 0, 0},
{1, 1, 1, 0},
{0, 1, 0, 0},
{1, 1, 0, 0}
};
Sortie attendue :
long long expected = 16;
Entrée :
long[][] grid = new long[][] {
new long[] {0, 1, 0, 0},
new long[] {1, 1, 1, 0},
new long[] {0, 1, 0, 0},
new long[] {1, 1, 0, 0}
};
Sortie attendue :
long expected = 16;
Explication
7 land cells have 28 sides; 6 shared edges remove 12: perimeter 16.
Entrée :
grid = [
[1]
]
Sortie attendue :
expected = 4
Entrée :
std::vector<std::vector<long long>> grid = {
{1}
};
Sortie attendue :
long long expected = 4;
Entrée :
long[][] grid = new long[][] {
new long[] {1}
};
Sortie attendue :
long expected = 4;
Explication
A single land cell has 4 sides.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Each land cell contributes exposed sides, so count how often land touches water or the boundary.
Indice 2
A simple scan can add four sides per land cell and subtract for each shared edge with another land cell.
Indice 3
Be careful not to double-count shared borders, and remember that cells outside the grid behave like water.
Complexité attendue
O(rows × columns) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.