Monday, March 14, 2022

Leet Code 785. Is Graph Bipartite




package pep.Day41;

import java.util.*;

// method of alternate color code

public class LeetCode_Is_Graph_Bipartite_1 {
public static void main(String[] args) {
//int[][] graph = {{1, 2, 3}, {0, 2}, {0, 1, 3}, {0, 2}};
int[][] graph = {{1, 3}, {0, 2}, {1, 3}, {0, 2}};
System.out.println(isBipartite(graph));
System.out.println(isBipartite2(graph));
}

public static boolean isBipartite2(int[][] graph) {
//BFS
// 0(not meet), 1(black), 2(white)
int[] visited = new int[graph.length];

for (int i = 0; i < graph.length; i++) {
if (graph[i].length != 0 && visited[i] == 0) {
visited[i] = 1;
Queue<Integer> q = new LinkedList<>();
q.offer(i);
while (!q.isEmpty()) {
int current = q.poll();
for (int c : graph[current]) {
                        // ADD ALTERNATE COLOR CODE
if (visited[c] == 0) {
visited[c] = (visited[current] == 1) ? 2 : 1;
q.offer(c);
} else {
                            // COLOR OF CHILD AND PARENT NODE SHOULD NOT BE SAME
if (visited[c] == visited[current])
                                return false;
}
}
}

}
}

return true;
}

public static boolean isBipartite(int[][] graph) {
int[] visited = new int[graph.length];
Arrays.fill(visited, -1);

for (int i = 0; i < visited.length; i++) {
if (visited[i] == -1)
if (!dfs(graph, i, visited))
return false;

}

return true;
}

public static boolean dfs(int[][] graph, int src, int[] visited) {
Queue<Integer> queue = new LinkedList<>();
queue.add(src);
int level = 0;

while (!queue.isEmpty()) {
int size = queue.size();

while (size-- > 0) {

int out = queue.remove();
// pehle se visited me present hai
if (visited[out] != -1) {
// conflict check krenge
if (visited[out] % 2 != level % 2)
return false;

}
// yha tak pauche to visited nhi tha
visited[out] = level;

for (int nbr : graph[out])
if (visited[nbr] == -1)
queue.add(nbr);
}
level++;
}
return true;
}


}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...