https://leetcode.com/problems/last-day-where-you-can-still-cross/
對總共的天數進行 binary search,然後使用 dfs 來看是否能夠從最上面走到最下面。
這邊的 update
是看 cur(當前的 grid 更新到第幾天) 跟 mid。如果 cur < mid
,代表需要更新到第 mid 天,因此把 grid 變成 -1。反過來的話則是把 grid 變成 0。
dfs 中,把走過的 grid 變成 mid,因此遇到 mid 或是 -1 的時候,代表無法再走下去了。
|
|
time complexity: $O(\log(row \times col) \times row \times col)$
space complextiy: $O(row \times col)$
其中 update
的複雜度會是 $O(row \times col)$,因為每一次只會更新 binary search range 的一半,會是 $(row \times col) \sum_{k = 1}^{\log(row \times col)}\frac{1}{2^k} = row \times col$。
另一個解法是 disjoint set。
從最後一天往前看,看什麼時候可以從最上面走到最下面。
特別注意的是,這邊多建立了兩個 node,分別代表最上面一排跟最下面一排。
每一天的最後只需要檢查最上面的一列跟最下面的一列有沒有一樣的 parent,有的話,就代表可以從最上面走到最下面。
為了快速檢查這件事情,把第一列的 node 都連到 n,最後一列連到 n + 1,這樣只需要看 find(parent, n) == find(parent, n + 1)
即可。
|
|
time complexity: $O(row \times col)$
space complextiy: $O(row \times col)$