İçeriğe atla
ΣDSA Patterns
Menü
Dil

Izgara ve Graf BFS

Rehber 2 / 6 · Yol 2 / 6

Interactive

Zihinsel model

Bu problem için animasyonlu çözüm. Adımları kaydır veya boşlukla duraklat; değişmezi yüksek sesle yeniden anlat.

Adım 1 / 8
S
.
.
T
.
#
.
.
.
.
.
.

queue = [S] · dist[S] = 0

Grid BFS: treat each cell as a node; 4-neighbors are edges. Seed the queue at the start.

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Number of Islands

Problem (restated)

Given a 2D grid of ‘1’ (land) and ‘0’ (water), return the number of islands. An island is max 4-directionally connected land.

Intuition

Each unvisited land cell starts a component. Flood-fill (DFS/BFS) marks the whole island; count how many times you start a fill.

Approaches

DFS flood fill

Tested only
Time O(m·n)Space O(m·n) worst-case stack

Idea. Iterate cells; on land, increment count and DFS to mark all connected land as water/visited.

Walkthrough. Grid with two separate land blobs → count 2.

Trade-offs. DFS is concise; BFS uses explicit queue (safer stack depth on huge grids).

Solution
export function numIslands(grid: string[][]): number {
  if (!grid.length) return 0;
  const m = grid.length, n = grid[0]!.length;
  const dfs = (r: number, c: number) => {
    if (r < 0 || c < 0 || r >= m || c >= n || grid[r]![c] !== "1") return;
    grid[r]![c] = "0";
    dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1);
  };
  let count = 0;
  for (let r = 0; r < m; r++)
    for (let c = 0; c < n; c++)
      if (grid[r]![c] === "1") { count++; dfs(r, c); }
  return count;
}
export function numIslands(grid: string[][]): number {
  if (!grid.length) return 0;
  const m = grid.length, n = grid[0]!.length;
  const dfs = (r: number, c: number) => {
    if (r < 0 || c < 0 || r >= m || c >= n || grid[r]![c] !== "1") return;
    grid[r]![c] = "0";
    dfs(r + 1, c); dfs(r - 1, c); dfs(r, c + 1); dfs(r, c - 1);
  };
  let count = 0;
  for (let r = 0; r < m; r++)
    for (let c = 0; c < n; c++)
      if (grid[r]![c] === "1") { count++; dfs(r, c); }
  return count;
}

Template connection

Grid BFS/DFS connected components.

Reflection