Trung bình 1 đã giải Tỷ lệ chấp nhận 100.0%

Island Perimeter

Measure the coastline of land cells in a grid.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

0 ≤ rows, columns ≤ 200

Ví dụ

Ví dụ 1
Đầu vào:
grid = [
    [0, 1, 0, 0],
    [1, 1, 1, 0],
    [0, 1, 0, 0],
    [1, 1, 0, 0]
]

Kết quả mong đợi:
expected = 16
Đầu vào:
std::vector<std::vector<long long>> grid = {
    {0, 1, 0, 0},
    {1, 1, 1, 0},
    {0, 1, 0, 0},
    {1, 1, 0, 0}
};

Kết quả mong đợi:
long long expected = 16;
Đầu vào:
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}
};

Kết quả mong đợi:
long expected = 16;

Giải thích

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

Ví dụ 2
Đầu vào:
grid = [
    [1]
]

Kết quả mong đợi:
expected = 4
Đầu vào:
std::vector<std::vector<long long>> grid = {
    {1}
};

Kết quả mong đợi:
long long expected = 4;
Đầu vào:
long[][] grid = new long[][] {
    new long[] {1}
};

Kết quả mong đợi:
long expected = 4;

Giải thích

A single land cell has 4 sides.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 ННикита Python 865 ms - 5/5 Xem code

Học hỏi từ người khác

Giải pháp cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem mã của người khác và đánh giá AI. Đăng nhập và giải thử thách để tham gia thảo luận.