iT邦幫忙

2026 iThome 鐵人賽

DAY 3
1
Software Development

快樂演算法系列 第 3

Drone & gpt 為何電腦版依然不能輸入.. &417 v2

  • 分享至 

  • xImage
  •  

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);

}

未來還在地圖內 + 未來沒走過 + 未來高度 ≥ 現在高度 → 就往高處爬。


上一篇
Auto training & gpt 今天好怪 &417初版 明日再繼續
系列文
快樂演算法3
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言