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);
}
}
}
}
Related
I have created graph using Node and Edge class.
When I call traverseBFS method from start = 0. then It just stuck. cannot proceed further. When I use similar approach with HashMap<Integer,ArrayList<Integer>> this algorithm runs properly. Please help me how to fix this.
Complete Code
import java.util.*;
import java.io.*;
public class Dijkstra {
static class Node {
public int id;
public long dist;
public int par;
public Node(int a, long d, int b) {
id = a;
dist = d;
par = b;
}
}
static class Edge {
int to;
int weight;
public Edge(int a, int b) {
to = a;
weight = b;
}
}
static int vert;
static ArrayList<LinkedList<Edge>> list;
static int[] parent;
static long[] distance;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
vert = sc.nextInt();
int edges = sc.nextInt();
list = new ArrayList<>();
parent = new int[vert + 1];
distance = new long[vert + 1];
for (int i = 0; i <= vert; i++) {
list.add(i, new LinkedList<Edge>());
}
for (int i = 0; i < edges; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int w = sc.nextInt();
list.get(u).add(new Edge(v, w));
list.get(v).add(new Edge(u, w));
}
traverseBFS(0);
}
public static void traverseBFS(int start) {
System.out.print("\nBFS >> \n");
boolean visited[] = new boolean[vert];
LinkedList<Integer> q = new LinkedList<>();
q.add(start);
visited[start] = true;
while (!q.isEmpty()) {
int s = q.poll();
System.out.print(s + " ");
LinkedList<Edge> temp = list.get(s);
for (Edge var : temp) {
if (!visited[var.to]) {
visited[var.to] = true;
q.add(var.to);
}
}
}
}
}
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
BFS >>
0
When posting mre consider hard coding test data, to make it easier to run a test:
public static void main(String[] args) {
int[][] neighbours = {
{1,2,2},
{2,5,5},
{2,3,4},
{1,4,1},
{4,3,3},
{3,5,1}
};
vert = 5;
list = new ArrayList<>();
parent = new int[vert + 1];
distance = new long[vert + 1];
for (int i = 0; i <= vert; i++) {
list.add(i, new LinkedList<Edge>());
}
for (int i = 0; i < neighbours.length; i++) {
int u = neighbours[i][0];
int v = neighbours[i][1];
int w = neighbours[i][2];
list.get(u).add(new Edge(v, w));
list.get(v).add(new Edge(u, w));
}
traverseBFS(0);
}
A simple print out the graph created shows that node 0 is not connected to any other node:
Node 0 connected: []
Node 1 connected: [to 2, to 4]
Node 2 connected: [to 1, to 5, to 3]
Node 3 connected: [to 2, to 4, to 5]
Node 4 connected: [to 1, to 3]
Node 5 connected: [to 2, to 3]
To simplify the printout add toString method to Edge:
static class Edge {
int to;
int weight;
public Edge(int a, int b) {
to = a;
weight = b;
}
#Override
public String toString() {
return "to "+to;
}
}
and use
for(int node = 0; node < list.size(); node ++){
System.out.println("Node "+node +" connected: " + list.get(node));
}
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);
}
}
I have a JAVA program where I am creating graphs and I have a Breadth-First Search but I would like to change it to Depth First Search. What changes should I make in a code? Thanks for help in advance.
public class ConnectedComponents
{
static final int MAXV = 100;
static boolean processed[] = new boolean[MAXV];
static boolean discovered[] = new boolean[MAXV];
static int parent[] = new int[MAXV];
static void bfs(CCGraph g, int start)
{
Queue<Integer> q = new LinkedList<Integer>();
int i, v;
q.offer(start);
discovered[start] = true;
while (!q.isEmpty())
{
v = q.remove();
process_vertex(v);
processed[v] = true;
for (i = g.degree[v] - 1; i >= 0; i--)
{
if (!discovered[g.edges[v][i]])
{
q.offer(g.edges[v][i]);
discovered[g.edges[v][i]] = true;
parent[g.edges[v][i]] = v;
}
}
}
}
I think you should understand the difference between depth first search and breadth first search. The code for depth first search goes as follows:
public class ConnectedComponents
{
static final int MAXV = 100;
static boolean processed[] = new boolean[MAXV];
static boolean discovered[] = new boolean[MAXV];
static int parent[] = new int[MAXV];
static void dfs(CCGraph g, int vertex)
{
discovered[vertex] = true;
for (i = g.degree[vertex] - 1; i >= 0; i--)
{
if (!discovered[g.edges[vertex][i]])
{
parent[g.edges[v][i]]=vertex;
dfs(g.edges[v][i]]);
}
}
}
}
The basic difference is the order by which vertexes are tested. While BFS uses queue (FIFO: First In First Out), DFS use stack (LIFO: Last In First Out).
You could implement stack using LinkedList:
LinkedList<Integer> stack = new LinkedList<Integer>();
stack.pop(); //returns the top of the stack
For more information please post mcve including test data.
Full code of the program. The goal is to change bfs to dfs.
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class CCGraph
{
static final int MAXV = 100;
static final int MAXDEGREE = 50;
public int edges[][] = new int[MAXV + 1][MAXDEGREE];
public int degree[] = new int[MAXV + 1];
public int nvertices;
public int nedges;
CCGraph()
{
nvertices = nedges = 0;
for (int i = 1; i <= MAXV; i++)
degree[i] = 0;
}
void read_CCGraph(boolean directed)
{
int x, y;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices: ");
nvertices = sc.nextInt();
System.out.println("Enter the number of edges: ");
int m = sc.nextInt();
System.out.println("Enter the edges: <from> <to>");
for (int i = 1; i <= m; i++)
{
x = sc.nextInt();
y = sc.nextInt();
insert_edge(x, y, directed);
}
sc.close();
}
void insert_edge(int x, int y, boolean directed)
{
if (degree[x] > MAXDEGREE)
System.out.printf(
"Warning: insertion (%d, %d) exceeds max degree\n", x, y);
edges[x][degree[x]] = y;
degree[x]++;
if (!directed)
insert_edge(y, x, true);
else
nedges++;
}
void print_CCGraph()
{
for (int i = 1; i <= nvertices; i++)
{
System.out.printf("%d: ", i);
for (int j = degree[i] - 1; j >= 0; j--)
System.out.printf(" %d", edges[i][j]);
System.out.printf("\n");
}
}
}
public class ConnectedComponents
{
static final int MAXV = 100;
static boolean processed[] = new boolean[MAXV];
static boolean discovered[] = new boolean[MAXV];
static int parent[] = new int[MAXV];
static void bfs(CCGraph g, int start)
{
LinkedList<Integer> q = new LinkedList<Integer>();
int i, v;
q.offer(start);
discovered[start] = true;
while (!q.isEmpty())
{
v = q.remove();
process_vertex(v);
processed[v] = true;
for (i = g.degree[v] - 1; i >= 0; i--)
{
if (!discovered[g.edges[v][i]])
{
q.offer(g.edges[v][i]);
discovered[g.edges[v][i]] = true;
parent[g.edges[v][i]] = v;
}
}
}
}
static void initialize_search(CCGraph g)
{
for (int i = 1; i <= g.nvertices; i++)
{
processed[i] = discovered[i] = false;
parent[i] = -1;
}
}
static void process_vertex(int v)
{
System.out.printf(" %d", v);
}
static void connected_components(CCGraph g)
{
int c;
initialize_search(g);
c = 0;
for (int i = 1; i <= g.nvertices; i++)
{
if (!discovered[i])
{
c++;
System.out.printf("Component %d:", c);
bfs(g, i);
System.out.printf("\n");
}
}
}
static public void main(String[] args)
{
CCGraph g = new CCGraph();
g.read_CCGraph(false);
g.print_CCGraph();
connected_components(g);
}
}
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)
package examples;
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
The below 4 sections identifies user input for the rows and columns of two matrices.
Scanner userrows1 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userrows1.nextInt();
Scanner usercolumns1 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns1 = usercolumns1.nextInt();
Scanner userrows2 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userrows2.nextInt();
Scanner usercolumns2 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns2 = usercolumns2.nextInt();
This sets the objects matrix1 and matrix2 as belonging to the class Matrix
Matrix matrix1 = new Matrix(rows1, columns1);
Matrix matrix2 = new Matrix(rows2, columns2);
matrix1.ShowMatrix();
System.out.println("\n \n");
matrix2.ShowMatrix();
}
}
class Matrix {
int rows;
int columns;
int[][] values;
public Matrix(int r, int c) {
rows = r;
columns = c;
int[][] values = new int[r][c];
This originally served to allow the user to input values of a matrix one by one. For now I just set all values of the matrix to a certain value for simplicity.
int i;
int j;
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
//Scanner userelement = new Scanner(System.in);
//System.out.println("Enter number:");
//int element = userelement.nextInt();
values[i][j] = 1;
}
}
}
public void ShowMatrix() {
int k;
int l;
for(k = 0; k < rows; k++) {
for(l = 0; l < columns; l++) {
System.out.println(values[k][l] + " ");
}
System.out.println("\n");
}
}
}
The code is above. In the final method in the class Matrix (the method is ShowMatrix), I am trying to print out the matrix. However, I am using the general values matrix here and it says:
Exception in thread "main" java.lang.NullPointerException
at examples.Matrix.ShowMatrix(MatrixMultiplication.java:75)
at examples.MatrixMultiplication.main(MatrixMultiplication.java:29)
Can anyone diagnose the issue? Much thanks as I'm still very new to Java.
You've not instantiate the field [][]values (There is a local declaration of int[][] values).
public Matrix(int r, int c) {
rows = r;
columns = c;
int[][] values = new int[r][c]; <-- Remove this
values = new int[r][c];
....
}
Just remove the package line if you are using the terminal or command prompt.
package examples;
Working Code:
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner userrows1 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userrows1.nextInt();
Scanner usercolumns1 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns1 = usercolumns1.nextInt();
Scanner userrows2 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userrows2.nextInt();
Scanner usercolumns2 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns2 = usercolumns2.nextInt();
Matrix matrix1 = new Matrix(rows1, columns1);
Matrix matrix2 = new Matrix(rows2, columns2);
matrix1.ShowMatrix();
System.out.println("\n \n");
matrix2.ShowMatrix();
}
}
class Matrix {
int rows;
int columns;
int[][] values;
public Matrix(int r, int c) {
rows = r;
columns = c;
//int[][] values = new int[r][c];
this.values = new int[r][c];
int i;
int j;
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
this.values[i][j] = 1;
}
}
}
public void ShowMatrix() {
int k;
int l;
for(k = 0; k < this.rows; k++) {
for(l = 0; l < this.columns; l++) {
System.out.print(this.values[k][l] + " ");
}
System.out.println("\n");
}
}
}
One more suggestion is that there is no need of creating new instance/object for Scanner class for each row and column.
Scanner userInput = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userInput.nextInt();
System.out.println("Enter number of columns for matrix 2");
int columns1 = userInput.nextInt();
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userInput.nextInt();
System.out.println("Enter number of columns for matrix 2");
int columns2 = userInput.nextInt();