【并查集】LeetCode 990. 等式方程的可满足性
题目链接
思路
并查集模板题,模板可以参考 常用算法模板。将字母视为结点,==
表示有路径,!=
表示无路径。
- 遍历
x == y
,建立图前驱关系 - 遍历
x != y
,检查是否和前驱关系对应 - 如果不对应,立即返回
false
- 全部遍历完成说明没有问题,返回
true
代码
class Solution {
private int[] pre = new int[26 + 3];
public boolean equationsPossible(String[] equations) {
init(26);
// build graph
for(String equation : equations){
if(equation.charAt(1) == '!'){
continue;
}
int indexFrom = equation.charAt(0) - 'a';
int indexTo = equation.charAt(3) - 'a';
mix(indexFrom, indexTo);
}
for(String equation : equations){
if(equation.charAt(1) == '!'){
int indexFrom = equation.charAt(0) - 'a';
int indexTo = equation.charAt(3) - 'a';
if(find(indexFrom) == find(indexTo)){
return false;
}
}
}
return true;
}
void init(int n) {
for(int i = 0; i < n; i++){
pre[i] = i;
}
}
private void mix(int a, int b) {
int fa = find(a);
int fb = find(b);
if(fa != fb){
pre[fb] = fa;
}
}
private int find(int x) {
int r = x;
while(r != pre[r]){
r = pre[r];
}
merge(r, x);
return r;
}
private void merge(int r, int x) {
int i = x, j;
while(pre[i] != r){
j = pre[i];
pre[i] = r;
i = j;
}
}
}