continue 就是換下一個方向
—
if not (0 <= nextRow < rows and 0 <= nextCol < cols):檢查下一格有沒有跑出地圖。例如 row=-1 就不能走,所以跳過
—
要知道「哪些格子能到 Pacific」和「哪些格子能到 Atlantic」,這是兩個不同集合;最後才知道哪些格子同時存在兩邊。
—
0,col = 最上面 Pacific;
rows-1,col = 最下面 Atlantic;
row,0 = 最左邊 Pacific;
row,cols-1 = 最右邊 Atlantic。
—
// ① 有沒有超出地圖?
if (nextRow < 0 || nextRow >= rows ||
nextCol < 0 || nextCol >= cols)
continue;
// ② 高度能不能逆流?
if (height[nextRow][nextCol] < height[row][col])
continue;
① 是地圖範圍;② 才是高度規則。兩件完全不同的事。
—
if (nextRow >= 0 && nextRow < rows &&
nextCol >= 0 && nextCol < cols &&
!visited[nextRow][nextCol] &&
height[nextRow][nextCol] >= height[row][col]) {
dfs(nextRow, nextCol, visited);
}
未來還在地圖內 + 未來沒走過 + 未來高度 ≥ 現在高度 → 就往高處爬。