Tutte le sfide
Media 1 risolta 100.0% di accettazione

Island Perimeter

Measure the coastline of land cells in a grid.

Cosa imparerai

  • Count land edges that touch water
  • Check four neighbors per cell
  • Handle grid borders

Problema

Mostra traduzione

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.

Vincoli

0 ≤ rows, columns ≤ 200

Esempi

Esempio 1
Input:
grid = [
    [0, 1, 0, 0],
    [1, 1, 1, 0],
    [0, 1, 0, 0],
    [1, 1, 0, 0]
]

Output atteso:
expected = 16
Input:
std::vector<std::vector<long long>> grid = {
    {0, 1, 0, 0},
    {1, 1, 1, 0},
    {0, 1, 0, 0},
    {1, 1, 0, 0}
};

Output atteso:
long long expected = 16;
Input:
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}
};

Output atteso:
long expected = 16;

Spiegazione

7 land cells have 28 sides; 6 shared edges remove 12: perimeter 16.

Esempio 2
Input:
grid = [
    [1]
]

Output atteso:
expected = 4
Input:
std::vector<std::vector<long long>> grid = {
    {1}
};

Output atteso:
long long expected = 4;
Input:
long[][] grid = new long[][] {
    new long[] {1}
};

Output atteso:
long expected = 4;

Spiegazione

A single land cell has 4 sides.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Each land cell contributes exposed sides, so count how often land touches water or the boundary.

Suggerimento 2

A simple scan can add four sides per land cell and subtract for each shared edge with another land cell.

Suggerimento 3

Be careful not to double-count shared borders, and remember that cells outside the grid behave like water.

Complessità attesa

O(rows × columns) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 Н"Никита "Programmer" Python 865 ms - 5/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 1 soluzione completa sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.