【算法】leetcode 990. 等式方程的可滿足性(並查集)

問題來源

990. 等式方程的可滿足性
給定一個由表示變量之間關係的字符串方程組成的數組,每個字符串方程 equations[i] 的長度爲 4,並採用兩種不同的形式之一:"a==b""a!=b"。在這裏,a 和 b 是小寫字母(不一定不同),表示單字母變量名。

只有當可以將整數分配給變量名,以便滿足所有給定的方程時才返回 true,否則返回 false。

示例 1:
    輸入:["a==b","b!=a"]
    輸出:false
    解釋:如果我們指定,a = 1 且 b = 1,那麼可以滿足第一個方程,但無法滿足第二個方程。沒有辦法分配變量同時滿足這兩個方程。

示例 2:
    輸入:["b==a","a==b"]
    輸出:true
    解釋:我們可以指定 a = 1 且 b = 1 以滿足滿足這兩個方程。

示例 3:
    輸入:["a==b","b==c","a==c"]
    輸出:true

示例 4:
    輸入:["a==b","b!=c","c==a"]
    輸出:false

示例 5:
    輸入:["c==c","b==d","x!=z"]
    輸出:true


提示:
    1 <= equations.length <= 500
    equations[i].length == 4
    equations[i][0] 和 equations[i][3] 是小寫字母
    equations[i][1] 要麼是 '=',要麼是 '!'
    equations[i][2]'='

官方解析


代碼


"""
需求分析:
    等式方程的可滿足性:只有當可以將整數分配給變量名,以便滿足所有給定的方程時才返回 true,否則返回 false。
    1 <= equations.length <= 500
    equations[i].length == 4
    equations[i][0] 和 equations[i][3] 是小寫字母
    equations[i][1] 要麼是 '=',要麼是 '!'
    equations[i][2] 是 '='
    
思路:使用數據結構:並查集UnionFind
    先遍歷所有等式方程,存儲所有不等式關係,相同的值存入並查集
    遍歷所有不等關係,通過並查集進行檢查
"""


class Solution:
    class UnionFind:
        def __int__(self):
            self.parent = list(range(26))

        def find(self, index):
            if index == self.parent[index]:
                return index
            self.parent[index] = self.find(self.parent[index])  # 路徑壓縮
            return self.parent[index]

        def union(self, index1, index2):
            self.parent[self.find(index1)] = self.find(index2)

    def equationsPossible(self, equations) -> bool:
        not_equal = list()
        uf = Solution.UnionFind()
        uf.parent = list(range(26))

        # 先遍歷所有等式方程,存儲所有不等式關係,相同的值存入並查集
        for equation in equations:
            a, b = ord(equation[0]) - ord('a'), ord(equation[-1]) - ord('a')
            if equation[1] == '!':  # 不等關係,先存儲起來
                not_equal.append((a, b))
            else:  # 使用並查集保存相等關係
                uf.union(a, b)

        # 遍歷所有不等關係,通過並查集進行檢查
        for item in not_equal:
            if uf.find(item[0]) == uf.find(item[1]):
                return False
        return True

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章