pranay_teja
2/10/2019 - 7:38 AM

LeetCode-Satisfiability of Equality Equations


// https://leetcode.com/problems/satisfiability-of-equality-equations/
class Solution {
public:
    void DFS(vector< vector<int> > g, int s, map<int,bool> &visited,
             vector<int> &color,int &gcount)
    {
        visited[s]=true;
        color[s]=gcount;
        for(int i=0;i<g[s].size();i++){
            if(!visited[g[s][i]]){
                DFS(g,g[s][i],visited,color,gcount);
            }
        }
    }
    bool equationsPossible(vector<string> equations) {
        vector< vector<int> > g(26);
        for(int i=0;i<equations.size();i++){
            if(equations[i][1] == '='){
                g[equations[i][0]-'a'].push_back(equations[i][3]-'a');
                g[equations[i][3]-'a'].push_back(equations[i][0]-'a');
            }
        }
        map<int,bool> visited;
        int gcount=0;
        vector<int> color(26,-1);
        for(int i=0;i<26;i++){
            if(!visited[i]){
                gcount++;
                DFS(g,i,visited,color,gcount);
            }
        }
        for(int i=0;i<equations.size();i++){
            if(equations[i][1] == '!'){
                if(equations[i][0] == equations[i][3]){
                    return false;
                }
                if(color[equations[i][0]-'a'] == color[equations[i][3]-'a']){
                    return false;
                }
            }
        }
        return true;
    }
};