Question to find Bfs path ,, i am able to code bfs path if the graph have vertices marked as 0,1,2,3,4,,like this
But can't able to apply adjacency matrix how to solve bfs for graph like 5,10,15,20
attached images what i have coded
solution
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Bfs {
public static void bfsTraversal(int[][] adjMatrix) {
Queue<Integer> pendingVertices = new LinkedList<>();
boolean[] visited = new boolean[adjMatrix.length];
visited[0] = true;
pendingVertices.add(0);
while (!pendingVertices.isEmpty()) {
int currentVertex = pendingVertices.poll();
System.out.print(currentVertex + " ");
for (int i = 0; i < adjMatrix.length; i++) {
if (adjMatrix[currentVertex][i] == 1 && !visited[i]) {
pendingVertices.add(i);
visited[i] = true;
}
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int v = s.nextInt();
int e = s.nextInt();
int[][] adjMatrix = new int[v][v];
for (int i = 0; i < e; i++) {
int v1 = s.nextInt();
int v2 = s.nextInt();
adjMatrix[v1][v2] = 1;
adjMatrix[v2][v1] = 1;
}
bfsTraversal(adjMatrix);
}
}
Click here for Question for bfs like vertices 0,1,2,3,4...
Click here for ,How i want to solve this for bfs like vertices 5,10,15,20...
And i want to do the same for graph like this ,,can't get logic
Solved by mapping the input with 0,1,2,3.... and maintained a reverseMap
Click here to view the Solution
If you know the range of the numbers, you can let the numbers 5, 10, 15 and 20 be the IDs of the nodes and store the indices of the nodes in a seperate array. Suppose the name of the array is IndexLookupArray, if you want to lookup the index of a node with ID x you can find it in IndexLookupArray[x]. And the rest of the code should be the same. If the range of the numbers is unknown or if it's too big to fit in an array, you can store the indices in a hash map for example and do the same thing.
You can write something like this:
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Bfs {
public static void bfsTraversal(int[][] adjMatrix) {
Queue<Integer> pendingVertices = new LinkedList<>();
boolean[] visited = new boolean[adjMatrix.length];
visited[0] = true;
pendingVertices.add(0);
while (!pendingVertices.isEmpty()) {
int currentVertex = pendingVertices.poll();
System.out.print(currentVertex + " ");
for (int i = 0; i < adjMatrix.length; i++) {
if (adjMatrix[currentVertex][i] == 1 && !visited[i]) {
pendingVertices.add(i);
visited[i] = true;
}
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int idx = 0;
int range = s.nextInt();
int v = s.nextInt();
int e = s.nextInt();
int[] IndexLookupArray = new int[range + 1]; // range + 1 since IndexLookupArray[range] should be accessible.
int[][] adjMatrix = new int[v][v];
Arrays.fill(IndexLookupArray, 0, range + 1, -1);
for (int i = 0; i < e; i++) {
int v1 = s.nextInt();
if (IndexLookupArray[v1] == -1)
{
IndexLookupArray[v1] = idx;
idx++;
}
v1 = IndexLookupArray[v1];
int v2 = s.nextInt();
if (IndexLookupArray[v2] == -1)
{
IndexLookupArray[v2] = idx;
idx++;
}
v2 = IndexLookupArray[v2];
adjMatrix[v1][v2] = 1;
adjMatrix[v2][v1] = 1;
}
bfsTraversal(adjMatrix);
}
}
Related
I am new at Java. Can anyone please "implement BFS in Java with the following algorithm" given in that below photo?
Algorithm.jpg
Code to implement:
import java.util.Scanner;
public class BFS{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int[][] graph = takeInputGraph(sc);
System.out.println("Give input of the source node");
int s = sc.nextInt();
bfs(graph,s);
}
public static int[][] takeInputGraph(Scanner sc){
System.out.println("Input the number of nodes in the graph");
int node = sc.nextInt();
System.out.println("Input the number of edges in the graph");
int edge = sc.nextInt();
int[][] mat = new int[node][node];
for(int c=0; c<edge; c++){
System.out.println("Enter the first node of the "+(c+1)+"th edge");
int node1 = sc.nextInt();
System.out.println("Enter the second node of the "+(c+1)+"th edge");
int node2 = sc.nextInt();
mat[node1][node2] = 1;
mat[node2][node1] = 1;
}
return mat;
}
public static void bfs(int[][] g, int s){
}
}
public static void bfs(int[][] g, int s){
int[] d = new int[g.length], // distances
p = new int[g.length]; // previous node
Arrays.fill(d, Integer.MAX_VALUE); // set all distances to infinity
Arrays.fill(p, -1);
d[s] = 0; // distance to starting node is 0
Queue<Integer> q = new LinkedList<>();
q.add(s);
while(!q.isEmpty()){
int u = q.poll();
for(int v = 0; v < g.length; v++){
if(g[u][v] == 1 // edge exists
&& d[u] + 1 < d[v]){ // distance is less
d[v] = d[u] + 1;
p[v] = u;
q.add(v);
}
}
}
}
I have to write a divide-and-conquer program to solve the following problem. Let A[1..n] and B[1..n] be two arrays of distinct integers, each sorted in an increasing order.Find the nth smallest of the 2n combined elements. I can not merge the two arrays. My program must be in O(log n) time.
I have written my program but have no clue how to determine if it meets the requirement of the run time.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// this section of code will require user input to have the value of n to be set
Scanner sc = new Scanner(System.in);
System.out.print(("What number would you like to set n equal to : "));
int value = sc.nextInt();
// this section of code set the two array only to hold the value of n
Random rand = new Random();
ArrayList<Integer> setA = new ArrayList<Integer>();
for (int i = 0; i < value; i++) {
int picks = rand.nextInt(1000);
setA.add(picks);
}
Collections.sort(setA);
System.out.println("A1: "+ setA);
ArrayList<Integer> setX = new ArrayList<Integer>();
for (int k = 0; k < value; k++) {
int picks = rand.nextInt(1000);
setX.add(picks);
}
Collections.sort(setX);
System.out.println("A2: "+ setX);
ArrayList<Integer> afinal = new ArrayList<Integer>();
int r = 0;
int f = 0;
int q = 0;
while(afinal.size()!= value) {
if(setA.get(r) < setX.get(f)) {
q = setA.get(r);
afinal.add(q);
r++;
}else {
q = setX.get(f);
afinal.add(q);
f++;
}
}
System.out.println("");
System.out.println(afinal);
int w = value - 1;
int ans = afinal.get(w);
System.out.println("");
System.out.println("The nth smallest integer is "+ ans);
}
}
You can calculate runtime with System.currentTimeMillis().
What we want to do is get the current time before the program runs, then get the time after the program runs. We then handle the two times accordingly.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
long before = System.currentTimeMillis();
// this section of code will require user input to have the value of n to be set
Scanner sc = new Scanner(System.in);
System.out.print(("What number would you like to set n equal to : "));
int value = sc.nextInt();
// this section of code set the two array only to hold the value of n
Random rand = new Random();
ArrayList<Integer> setA = new ArrayList<Integer>();
for (int i = 0; i < value; i++) {
int picks = rand.nextInt(1000);
setA.add(picks);
}
Collections.sort(setA);
System.out.println("A1: "+ setA);
ArrayList<Integer> setX = new ArrayList<Integer>();
for (int k = 0; k < value; k++) {
int picks = rand.nextInt(1000);
setX.add(picks);
}
Collections.sort(setX);
System.out.println("A2: "+ setX);
ArrayList<Integer> afinal = new ArrayList<Integer>();
int r = 0;
int f = 0;
int q = 0;
while(afinal.size()!= value) {
if(setA.get(r) < setX.get(f)) {
q = setA.get(r);
afinal.add(q);
r++;
}else {
q = setX.get(f);
afinal.add(q);
f++;
}
}
System.out.println("");
System.out.println(afinal);
int w = value - 1;
int ans = afinal.get(w);
System.out.println("");
System.out.println("The nth smallest integer is "+ ans);
long after = System.currentTimeMillis();
}
}
In the example above, we've got the two times. Now what do we do?
We can subtract them to get the difference in times (by milliseconds).
Like so:
long ellapsedMilliseconds = after-before;
If you want to get the elapsed time in seconds, divided ellapsedMilliseconds by 100.
So the final code should be;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
long before = System.currentTimeMillis();
// this section of code will require user input to have the value of n to be set
Scanner sc = new Scanner(System.in);
System.out.print(("What number would you like to set n equal to : "));
int value = sc.nextInt();
// this section of code set the two array only to hold the value of n
Random rand = new Random();
ArrayList<Integer> setA = new ArrayList<Integer>();
for (int i = 0; i < value; i++) {
int picks = rand.nextInt(1000);
setA.add(picks);
}
Collections.sort(setA);
System.out.println("A1: "+ setA);
ArrayList<Integer> setX = new ArrayList<Integer>();
for (int k = 0; k < value; k++) {
int picks = rand.nextInt(1000);
setX.add(picks);
}
Collections.sort(setX);
System.out.println("A2: "+ setX);
ArrayList<Integer> afinal = new ArrayList<Integer>();
int r = 0;
int f = 0;
int q = 0;
while(afinal.size()!= value) {
if(setA.get(r) < setX.get(f)) {
q = setA.get(r);
afinal.add(q);
r++;
}else {
q = setX.get(f);
afinal.add(q);
f++;
}
}
System.out.println("");
System.out.println(afinal);
int w = value - 1;
int ans = afinal.get(w);
System.out.println("");
System.out.println("The nth smallest integer is "+ ans);
long after = System.currentTimeMillis();
long ellapsedMilliseconds = after-before;
System.out.println("Execution time: "+elapsedMilliseconds);
}
}
I'm writing a program to find the longest path for a DAG with input from standard in.I finally got it to compile, with it saying it is using unchecked or unsafe operations due to my Array list, but I am getting an index out of bounds error and it feels like I have tried changing every loop I must be missing something, thanks in advanced for any tips.
Here is my code:
import java.io.*;
import java.util.*;
public class countLongPaths
{
static final int NINF = Integer.MIN_VALUE;
public class AdjListNode
{
private int v;
private int weight;
AdjListNode(int inV, int inW)
{
v = inV;
weight = inW;
}
int getV()
{
return v;
}
int getWeight()
{
return weight;
}
}//end of adj list class
public class Graph
{
private int V;
private LinkedList<AdjListNode>adj[];
//set up graph with given number of verticies
Graph(int v)
{
V=v;
adj = new LinkedList[V];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList<AdjListNode>();
}
//function to add edges to graph
void addEdge(int u, int v, int weight)
{
AdjListNode node = new AdjListNode(v,weight);
adj[u].add(node);// Add v to u's list
}
//function to set order to go through vertices
void setOrder(int v, Boolean visited[], Stack stack)
{
//Set node to visited when on it
visited[v] = true;
Integer i;
//for all nodes connected to current repeat
Iterator<AdjListNode> it = adj[v].iterator();
while (it.hasNext())
{
AdjListNode node =it.next();
if (!visited[node.getV()])
setOrder(node.getV(), visited, stack);
}
//Once done with current add it to the stack
stack.push(new Integer(v));
}
//function to find longest paths from s
int longestPath()
{
Stack stack = new Stack();
int LP[] = new int[V];
//set all vertices to unvisited
Boolean visited[] = new Boolean[V];
for(int i = 1; i <= V; i++)
visited[i] = false;
//call set order function from each vertex
for (int i = 1; i <= V; i++)
{
if(visited[i] == false)
setOrder(i, visited, stack);
}
//initialize distaces to all verices as negative infinity
//set distace to source to 0
LP[1] = 0;
for(int i = 2; i <= V; i++)
LP[i] = NINF;
//go through vertices in order
while(stack.empty() == false)
{
int u = (int)stack.pop();
//update LP for adj vertices
Iterator<AdjListNode> it;
if (LP[u] != NINF)
{
it = adj[u].iterator();
while (it.hasNext())
{
AdjListNode i = it.next();
if(LP[i.getV()] < LP[u] + i.getWeight())
LP[i.getV()] = LP[u] + i.getWeight();
}
}
}
return LP[V];
}
}//end of graph class
//Method to make a new graph
public Graph newGraph(int number)
{
return new Graph(number);
}
public static void main(String[]args)
{
countLongPaths n = new countLongPaths();
int GN = 0;
int count = 1;
Scanner scan = new Scanner(System.in);
GN = scan.nextInt();
while (count<= GN)
{
int N = 0;// nodes
int M = 0;//edges
N = scan.nextInt();
M = scan.nextInt();
//setup a new graph
Graph g = n.newGraph(N);
//set edges for new graph
for(int i = 1; i <= M; i ++)
{
int I = scan.nextInt();
int J = scan.nextInt();
int W = scan.nextInt();
g.addEdge(I, J, W);
}
int dist = 0;
dist = g.longestPath();
System.out.println("graph number: " + count);
System.out.println("longest path: " + dist);
System.out.println("number of longest paths: ");
System.out.println();
count++;
}//end of while
}//end main
}//end program
EDIT 1
with current code this is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at countLongPaths$Graph.<init>(countLongPaths.java:36)
at countLongPaths.newGraph(countLongPaths.java:108)
at countLongPaths.main(countLongPaths.java:127)
As your stack trace says, the exception occurs in your Graph class constructor.
More specifically it happens inside the only line in your loop:
adj = new LinkedList[V];
for (int i = 0; i <= v; ++i)
adj[i] = new LinkedList<AdjListNode>();
Assuming you've meant both lowercase v and uppercase V to be the same variable, you're defining an array of size V which is indexed from 0 to V-1, but you're running on it from 0 to V (your condition is i <= V), which is why you're getting an IndexOutOfBoundsException.
Simply change the loop's condition (remove the =):
for (int i = 0; i < v; ++i)
https://drive.google.com/file/d/0B-KJ4TN8DpT9Zk1LTWpxRGZqZEk/view?usp=sharing
This is the link to my code. Please review it and share your thought in this (I am a beginner in Algorithms)
Actually, the code first wants for the number of test cases and then the size of the test case and number of edges in one line, then there are lines containing edges, last line of one test case is the source..here is a input example:
2
4 2
1 2
1 3
1
3 1
2 3
2
That means to test cases, for the 1st test case: 4 nodes and 2 edges, 1 is the source for 1st case...
Below is my code snippet:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Solution {
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
Scanner sc;
int test = scan.nextInt();
scan.nextLine();
for(int i =0; i < test; i++)
{
String temp = scan.nextLine();
sc = new Scanner(temp);
int size = sc.nextInt();
int edge = sc.nextInt();
int bfs[][] = new int[size+1][size+1];
for(int j = 0; j < edge; j++)
{
temp = scan.nextLine();
sc = new Scanner(temp);
int row = sc.nextInt();
int clm = sc.nextInt();
bfs[row][clm] = 1;
bfs[clm][row] = 1;
}
int src = scan.nextInt();
scan.nextLine();
int visit[] = search(src, bfs);
for(int j = 1; j < visit.length; j++)
{
if(visit[j] == 1)
{
System.out.print("6"+" ");
}
else if(j != src)
{
System.out.print("-1 ");
}
}
System.out.println();
}
}
public static int[] search(int src, int[][]bfs)
{
int [] visit = new int[bfs.length];
int[] color = new int[bfs.length];
color[src] = 1;
Queue q = new LinkedList();
q.add(src);
while(q.size() != 0)
{
int temp = (int) q.remove();
for(int i = 1; i < bfs[temp].length; i++)
{
if(bfs[temp][i] == 1 && color[i] == 0)
{
visit[i] = 1;
color[i] = 1;
q.add(i);
}
}
}
return visit;
}
}
I'm writing a code that should theoretically take a text file representation of a graph with a number of vertices, edges, and a list of edges, and use depth-first-search to determine if it's bipartite. However I'm using an Arraylist of lists to store the adjacency lists, and I keep getting java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 error at the for loop in the childColor method
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.*;
import static java.lang.System.*;
import java.util.*;
public class detect_bipartite {
public static void main(String[] args){
int bipartCheck = 1;
List<Integer> numList = new ArrayList<Integer>();
File inFile = null;
//separate white space
if (0 < args.length) {
inFile = new File(args[0]);
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(inFile));
String text = null;
while ((text = reader.readLine()) != null) {
String[] tmp = text.split(" ");
for(String str: tmp)
if(!str.equals("")){
numList.add(Integer.parseInt(str));}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
int n = numList.get(0);
int m = numList.get(1);
List<Integer> edgeA = new ArrayList<Integer>();
List<Integer> edgeB = new ArrayList<Integer>();
for(int i=2; i<numList.size(); i++){
if(i%2==0){edgeA.add(numList.get(i));}
else if(i%2==1){edgeB.add(numList.get(i));}
}
List<List<Integer>> adjLists = new ArrayList<List<Integer>>(n);
for(int j = 1; j <= adjLists.size(); j++){ //get adjacency lists
for(int a=1; a <=edgeA.size(); a++){
if(edgeA.get(a)==j){ (adjLists.get(j)).add(edgeB.get(a));}
if(edgeB.get(a)==j){ (adjLists.get(j)).add(edgeA.get(a));}
}
}
int[] color = new int[n];
Arrays.fill(color, 0);
//0 = uncolored
//1 = red
//2 = blue
int bipart = childColor(n, 1, adjLists, color, 1);
if (bipart==0){bipartCheck = 0;}
for(int d = 0; d < n; d++) //for any disconnected graphs
{
if(color[d] == 0){
bipart = childColor(n, d, adjLists, color, 1);}
if (bipart==0){bipartCheck = 0;}
}
if(bipartCheck == 1){
System.out.println("Bipartite");
} else{
System.out.println("Not a Bipartite");
}
}
public static int childColor(int n, int node, List<List<Integer>> adjLists, int[] color, int nodeColor){
if(color[node] == nodeColor){
return 1;}
int bipart = 1;
int newColor;
if(nodeColor == 1){newColor = 2;}
else{newColor = 1;}
if(color[node] == newColor)
{return 0;}
color[node] = nodeColor;
for(int k = 0; k < adjLists.get(node).size(); k++){ **//This is the error line**
bipart = childColor(n, adjLists.get(node).get(k), adjLists, color, newColor);
if(bipart == 0)
{return 0;}
}
return bipart;
}
}
When you do:
List<List<Integer>> adjLists = new ArrayList<List<Integer>>(n);
You create an ArrayList with initial capacity n. This does not mean the list has size n though. In fact, since the list has no elements, its size is 0. Given that, 1 <= 0 is false and this loop is never executed:
for(int j = 1; j <= adjLists.size(); j++){ //get adjacency lists
for(int a=1; a <=edgeA.size(); a++){
if(edgeA.get(a)==j){ (adjLists.get(j)).add(edgeB.get(a));}
if(edgeB.get(a)==j){ (adjLists.get(j)).add(edgeA.get(a));}
}
}
So, when you call childColor(n, 1, adjLists, color, 1), adjLists is empty. When you try to access an element at index 1, by doing adjLists.get(node), there is no element, thus the IndexOutOfBoundsException.
Also note that Java lists and arrays indices start at 0, not 1.
To solve the problem, you could initialize all the lists before trying to use them:
List<List<Integer>> adjLists = new ArrayList<List<Integer>>(n);
for (int i = 0; i < n; i++) {
adjLists.add(new ArrayList<>());
}