幅優先探索 (BFS) で 東と 西の 両方の 海へ 流れる 場所を探す - LeetCode 417
島の
海外で定番の問題リスト 4 本のうち 2 本に入っています (Blind 75、NeetCode 150)
問題
m 行 n 列のheights をheights[r][c] は、
ある
- マスは
[行, 列]の 2 つの数で 表します。 返す順は 問いません。 例の 出力は、 下の 解き方で 返した ときの順です - m と n は 1 以上 200 以下、
高さは どれも 0 以上 100000 以下の整数です
入力と出力の例
例 1
左上の 1 と 2 は、
入力
heights = [[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]出力
[[0, 2], [1, 0], [1, 1],
[1, 2], [2, 0], [2, 1],
[2, 2]]例 2
まん中の 1 は
入力
heights = [[3, 3, 3],
[3, 1, 3],
[3, 3, 3]]出力
[[0, 0], [0, 1], [0, 2],
[1, 0], [1, 2],
[2, 0], [2, 1], [2, 2]]例 3
マスが 1 つだけの
入力
heights = [[5]]出力
[[0, 0]]図で見る
例 1 で、
面接での聞かれ方
面接では、
- 「高さの
地図で、 2 つの 海の 両方 へ水が 流れ出せる 場所を 全部返してください」 - 書き終えた
あとに 「マスごとに 水を 流してみる 書き方と 比べて、 どれだけ 速いですか?」 「なぜ海の 側から 逆に たどるのですか?」と 続けて 聞かれます - 「同じ
高さの マスへは 流れますか?」と、 条件の 端を 確かめられる こともあります
同じ
ヒント
まだ開いていません
付箋は 4 枚。下の段ほど答えに近づきます
ヒント 2
ヒント 3
ヒント 4答えに近い
アルゴリズムのチートシートの「グラフ探索と幅優先探索」に、
関わる学び
グラフ探索は、
まず 考える手順
段 1
まずは
段 2
向きを
段 3
東の
段 4
角の
解答
Python
Python
from collections import deque
MOVES = (
(1, 0), (-1, 0),
(0, 1), (0, -1),
)
def climb(
heights: list[list[int]],
starts: list[tuple[int, int]],
) -> set[tuple[int, int]]:
rows = len(heights)
columns = len(heights[0])
seen = set(starts)
queue = deque(starts)
while queue:
y, x = queue.popleft()
here = heights[y][x]
for move_y, move_x in MOVES:
to_y = y + move_y
to_x = x + move_x
if not 0 <= to_y < rows:
continue
if not 0 <= to_x < columns:
continue
if (to_y, to_x) in seen:
continue
there = heights[to_y][to_x]
if there < here:
continue
seen.add((to_y, to_x))
queue.append((to_y, to_x))
return seen
def both_seas(
heights: list[list[int]],
) -> list[list[int]]:
rows = len(heights)
columns = len(heights[0])
west = []
east = []
for y in range(rows):
west.append((y, 0))
east.append((y, columns - 1))
for x in range(columns):
west.append((0, x))
east.append((rows - 1, x))
from_west = climb(heights, west)
from_east = climb(heights, east)
both = from_west & from_east
cells = []
for y in range(rows):
for x in range(columns):
if (y, x) in both:
cells.append([y, x])
return cellsJavaScript
JavaScript
const MOVES = [
[1, 0], [-1, 0],
[0, 1], [0, -1],
];
function climb(heights, starts) {
const columns = heights[0].length;
const seen = new Set();
for (const [y, x] of starts) {
seen.add(y * columns + x);
}
const queue = [...starts];
let head = 0;
while (head < queue.length) {
const [y, x] = queue[head];
head++;
const here = heights[y][x];
for (const move of MOVES) {
const toY = y + move[0];
const toX = x + move[1];
const there =
heights[toY]?.[toX] ?? -1;
if (there < here) {
continue;
}
const key = toY * columns + toX;
if (seen.has(key)) {
continue;
}
seen.add(key);
queue.push([toY, toX]);
}
}
return seen;
}
function bothSeas(heights) {
const rows = heights.length;
const columns = heights[0].length;
const west = [];
const east = [];
for (let y = 0; y < rows; y++) {
west.push([y, 0]);
east.push([y, columns - 1]);
}
for (let x = 0; x < columns; x++) {
west.push([0, x]);
east.push([rows - 1, x]);
}
const fromWest = climb(heights, west);
const fromEast = climb(heights, east);
const cells = [];
for (let y = 0; y < rows; y++) {
for (let x = 0; x < columns; x++) {
const key = y * columns + x;
if (
fromWest.has(key) &&
fromEast.has(key)
) {
cells.push([y, x]);
}
}
}
return cells;
}Go
Go
type cell = [2]int
var moves = [4]cell{
{1, 0}, {-1, 0},
{0, 1}, {0, -1},
}
func climb(
heights [][]int, starts []cell,
) [][]bool {
rows := len(heights)
columns := len(heights[0])
seen := make([][]bool, rows)
for y := range seen {
seen[y] = make([]bool, columns)
}
for _, start := range starts {
seen[start[0]][start[1]] = true
}
queue := starts
head := 0
for head < len(queue) {
y, x := queue[head][0],
queue[head][1]
head++
here := heights[y][x]
for _, move := range moves {
toY, toX := y+move[0], x+move[1]
if toY < 0 || toY >= rows {
continue
}
if toX < 0 || toX >= columns {
continue
}
if seen[toY][toX] {
continue
}
if heights[toY][toX] < here {
continue
}
seen[toY][toX] = true
queue = append(queue,
cell{toY, toX})
}
}
return seen
}
func bothSeas(
heights [][]int,
) [][]int {
rows := len(heights)
columns := len(heights[0])
west := []cell{}
east := []cell{}
for y := range rows {
west = append(west, cell{y, 0})
east = append(east,
cell{y, columns - 1})
}
for x := range columns {
west = append(west, cell{0, x})
east = append(east,
cell{rows - 1, x})
}
fromWest := climb(heights, west)
fromEast := climb(heights, east)
cells := [][]int{}
for y := range rows {
for x := range columns {
if fromWest[y][x] &&
fromEast[y][x] {
cells = append(cells,
[]int{y, x})
}
}
}
return cells
}y はx はclimb は、heights[toY]?.[toX] ?? -1 は、-1 に-1 は
計算量
- 時間は O(m × n) です。
幅優先を 2 回しますが、 どちらでも、 どの マスも 待ち行列に 1 回だけ 入り、 出る たびに 4 方向の 隣を 見るだけです。 最後に 地図を 1 回なめて 答えを集めます - 使う
記憶は O(m × n) です。 海ごとの 「届いた」印と、 待ち行列です - 段 1 の
マスごとに 流す 書き方は O((m × n)²) です。 海が 2 つしかない ことを 使い、 出発点の 側を 入れ替えた ことで、 ここまで 減りました
よく ある間違い
- 登る
向きの 比べ方を 逆にする。 海から 逆に たどる 時は、 隣が 「同じか高い」なら 進みます。 流す 向きのまま 「低い」なら 進むと 書くと、 まったく 違う マスを集めます - 同じ
高さを 止めてしまう。 「高い」だけで 進むと、 例 2 のように 同じ 高さが 続く 所で 止まり、 届くはずの マスを 落とします。 比べるのは 「より 低ければ 止める」です - 角を
片方の 海に しか 入れない。 右上の 角を、 上の 端として 西の 海に だけ 入れ、 右の 端としての 東の 海を 忘れると、 1 行や 1 列の 地図で 答えが 欠けます。 行ごとと 列ごとに 両方の 端を 入れれば、 角は 自然に 両方 へ入ります
解答を動かした版 Python 3.12.14Node.js 22.23.4Go 1.24.6確認日 2026年10月30日
面接での 話し方の例
書き始める
「マスごとに
水を 流すと、 マスの 数の 2 乗かかります。 そこで 向きを 逆に して、 それぞれの 海に 面した マスから、 同じか 高い 隣へ 登る 幅優先を します。 届いた マスは、 その 海へ 流れ込める マスです。 2 回の 幅優先で 両方に 届いた マスを、 行と 列の 順に 集めます。 時間も 記憶も O(m × n) です。」
書き終えたら、
「例 1 の
東の 海で たどります。 下の 端の 7、 6、 5 と、 右の 端の 3、 4 から 始めます。 4 からは 隣の 9 へ 登れ、 7 からは 上の 8 へ 登れます。 3 の 左の 2 と、 8 の 上の 1 は 低いので 登れません。 西の 海からは 全部の マスに 届くので、 答えは 左上の 2 マスを 除いた 7 マスです。」