图论28(Leetcode990等式方程的可满足性)

代码:

class Solution {
    public boolean equationsPossible(String[] equations) {
        Map charToIndex = new HashMap<>();
        int charsCount=0;
        for(String equation:equations){
            Character ch1 = equation.charAt(0);
            Character ch2 = equation.charAt(3);
            if(!charToIndex.containsKey(ch1)){
                charToIndex.put(ch1,charsCount++);
            }
            if(!charToIndex.containsKey(ch2)){
                charToIndex.put(ch2,charsCount++);
            }
        }
        UnionFind uf = new UnionFind(charsCount);
        for(String equation:equations){
            if(equation.charAt(1)=='='){
                Character ch1 = equation.charAt(0);
                Character ch2 = equation.charAt(3);
                uf.union(charToIndex.get(ch1),charToIndex.get(ch2));
            }
        }
        for(String equation:equations){
            if(equation.charAt(1)=='!'){
                Character ch1 = equation.charAt(0);
                Character ch2 = equation.charAt(3);
                int p1 = uf.find(charToIndex.get(ch1));
                int p2 = uf.find(charToIndex.get(ch2));
                if(p1==p2)return false;
            }
        }
        return true;
    }
}

class UnionFind{
    int[] parent;
    public UnionFind(int n){
        parent = new int[n];
        for(int i=0;i

你可能感兴趣的:(图论,算法)