1. 程式人生 > 其它 >【1月打卡~Leetcode每日一題】947. 移除最多的同行或同列石頭(難度:中等)

【1月打卡~Leetcode每日一題】947. 移除最多的同行或同列石頭(難度:中等)

技術標籤:演算法python演算法資料結構leetcode

947. 移除最多的同行或同列石頭

n 塊石頭放置在二維平面中的一些整數座標點上。每個座標點上最多隻能有一塊石頭。
如果一塊石頭的 同行或者同列 上有其他石頭存在,那麼就可以移除這塊石頭。
給你一個長度為 n 的陣列 stones ,其中 stones[i] = [xi, yi] 表示第 i 塊石頭的位置,返回 可以移除的石子 的最大數量。

思路:使用並查集或DFS找連通域,同一個連通域最終肯定可以只剩下1個頂點,因此結果為n-連通域的個數

class Solution:
    def removeStones(self,
stones: List[List[int]]) -> int: n = len(stones) parent = list(range(n)) def find(index): if index != parent[index]: parent[index] = find(parent[index]) return parent[index] def union(index1,index2): parent[
find(index1)] = find(index2) for i in range(n): for j in range(i): if stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1]: union(i,j) return n - sum([i==parent[i] for i in range(n)])

時間複雜度O(n²)