Graph 1 Solutions
Graph 1 Solutions
[email protected]
Solution 1:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
class Solution{
int V = 4;
@SuppressWarnings("unchecked")
ArrayList <Integer> adj[] = new ArrayList[V];
for(int i = 0; i < 4; i++)
adj[i] = new ArrayList<Integer>();
addEdge(adj, 0, 1);
addEdge(adj, 1, 2);
addEdge(adj, 2, 0);
addEdge(adj, 2, 3);
if (isCyclicDisconntected(adj, V))
System.out.println("Yes");
else
System.out.println("No");
}
[email protected]
visited[s] = true;
q.add(s);
while (!q.isEmpty()){
int u = q.poll();
for (int i = 0; i < adj[u].size(); i++){
int v = adj[u].get(i);
if (!visited[v]){
visited[v] = true;
q.add(v);
parent[v] = u;
}
else if (parent[u] != v)
return true;
}
}
return false;
}
Solution 2:
import java.util.*;
class Solution{
[email protected]
int data;
Node left, right;
}
if (node.right != null){
qi.node = node.right;
qi.depth = depth + 1;
q.add(qi);
}
}
[email protected]
return 0;
}
System.out.println(minDepth(root));
}
}
Solution 3 :
import java.util.LinkedList;
import java.util.Queue;
[email protected]
this.y = y;
}
}
Q.add(new Ele(-1,-1));
while(!Q.isEmpty()){
boolean flag = false;
while(!isDelim(Q.peek())){
temp = Q.peek();
if(isValid(temp.x+1, temp.y) && arr[temp.x+1][temp.y] == 1){
if(!flag){
ans++;
flag = true;
}
[email protected]
arr[temp.x+1][temp.y] = 2;
temp.x++;
Q.add(new Ele(temp.x,temp.y));
temp.x--;
}
[email protected]
Q.remove();
}
Q.remove();
if (!Q.isEmpty())
{
Q.add(new Ele(-1,-1));
}
}
return (checkAll(arr))? -1: ans;
}
Solution 4 :
import java.io.*;
import java.util.*;
class Solution {
static int ROW, COL, count;
static boolean isSafe(int[][] M, int row, int col,
boolean[][] visited)
[email protected]
{
return (
(row >= 0) && (row < ROW) && (col >= 0)
&& (col < COL)
&& (M[row][col] == 1 && !visited[row][col]));
}
visited[row][col] = true;
for (int k = 0; k < 8; k++) {
if (isSafe(M, row + rowNbr[k], col + colNbr[k],
visited)) {
count++;
DFS(M, row + rowNbr[k], col + colNbr[k],
visited);
}
}
}
[email protected]
int M[][] = { { 0, 0, 1, 1, 0 },
{ 1, 0, 1, 1, 0 },
{ 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1 } };
ROW = 4;
COL = 5;
System.out.println(largestRegion(M));
}
}
Solution 5 :
import java.util.*;
class Solution {
static int shortestChainLen(String start,
String target,
Set<String> D){
if(start == target)
return 0;
if (!D.contains(target))
return 0;
int level = 0, wordlength = start.length();
Queue<String> Q = new LinkedList<>();
Q.add(start);
while (!Q.isEmpty()){
++level;
int sizeofQ = Q.size();
for (int i = 0; i < sizeofQ; ++i){
char []word = Q.peek().toCharArray();
Q.remove();
for (int pos = 0; pos < wordlength; ++pos){
[email protected]
char orig_char = word[pos];
for (char c = 'a'; c <= 'z'; ++c){
word[pos] = c;
if (String.valueOf(word).equals(target))
return level + 1;
if (!D.contains(String.valueOf(word)))
continue;
D.remove(String.valueOf(word));
Q.add(String.valueOf(word));
}
word[pos] = orig_char;
}
}
}
return 0;
}