Breadth First Traversal using adj Matrix - java

I'm writing breadth first, depth first, and depth first recursive traversal for the following graph:
From what I understand, the traversal should be 0 1 3 6 4 5 2...but i'm only getting that for the depth first traversal, and for the dfs(recursive) and BFS, I'm getting 0 1 3 6 2 4 5. I don't know which one is right and what I need to do to fix the problem.
Class
public void depthFirst(int vFirst,int n, int[] isvisited)
{ //vFirst = 0, n = 6
int v,i;
// st is a stack
st.push(vFirst);
while(!st.isEmpty())
{
v = st.pop();
if(isvisited[v]==0)
{
System.out.print(v);
isvisited[v]=1;
}
for ( i = 0; i <= n; i++)
{
if((adjMatrix[v][i] == 1) && (isvisited[i] == 0))
{
st.push(v);
isvisited[i]=1;
System.out.print(" " + i);
v = i;
}
}
}
}
public void depthFirstRecursive(int w) {
int j; //w = 0;
visited[w] = 1;
if (w == 0) {
System.out.print(w + " ");
}
for (j = 0; j <= 6; j++) {
if ((adjMatrix[w][j] == 1) && (visited[j] == 0)) {
System.out.print(j + " ");
depthFirstRecursive(j);
}
}
}
public void breadthFirst(int first, int p) {
int e; // first = 0; p = 6
int[] nodeVisited = new int[7];
que.add(first);
while (!que.isEmpty()) {
e = que.remove();
if(nodeVisited[e]==0)
{
System.out.print(e);
nodeVisited[e]=1;
}
for (int i = 0; i <= p; i++)
{
if((adjMatrix[e][i] == 1) && (nodeVisited[i] == 0))
{
que.add(e);
nodeVisited[i]=1;
System.out.print(" " + i);
e = i;
}
}
}
}
public static void main(String[] args) {
// 1 2 3 4 5 6 7
int[][] adjMatrix = { {0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 0},
{1, 0, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1},
{0, 1, 0, 0, 0, 0 ,0},
{0, 0, 1, 1, 1, 0, 0} };
new myGraphs(adjMatrix);
}

About following snippet in BFS:
que.add(e);
nodeVisited[i]=1;
System.out.print(" " + i);
e = i;
They why do you change e and add e to queue? It seems incorrect to me.

Non Recursive BFS using Queue:
public int[] breadthFirstSearch(int[][] adjacencyMatrix, int start) {
int totalNumberOfvertices = adjacencyMatrix.length;
boolean[] visited = new boolean[totalNumberOfvertices];
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = true;
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
list.add(queue.peek());
int currentFirstElementInQueue = queue.poll();
for (int i = 0; i < adjacencyMatrix.length; i++) {
if ((adjacencyMatrix[currentFirstElementInQueue][i] == 1) && (!visited[i])) {
queue.add(i);
visited[i] = true;
}
}
}
int[] result = new int[list.size()];
int i = 0;
Iterator<Integer> itr = list.iterator();
while (itr.hasNext()) {
result[i++] = itr.next();
}
return result;
}

public void BFS(int start)
{
int v=a.length;//a[][] is adj matrix declared globally
boolean visited[]=new boolean[v];//indexing done from 1 to n
LinkedList<Integer> queue=new LinkedList<Integer>();
visited[start]=true;
queue.add(start);
while(queue.size()!=0)
{
int x=queue.remove();
System.out.print(x+" ");
for (int i=1; i < v; i++)
if((a[x][i] == 1) && (!visited[i]))
{
queue.add(i);
visited[i]=true;
}
}
}

Related

Move all zeroes in a given array to the end and replace each non-zero element with the closest greater value, if any

Looking for the optimised solution for the below problem.
Given an unsorted array, we are required to move all zeroes to the end of the array and at same time find the next closest greater number of each element(non-zero) and return the same element incase if there is no next greater element for an element in the array .
Input = {6,1,5,0,0,3,8,6,4}
Output = {8,3,6,4,8,6,4,0,0}
I tried the below :
public class next_closest_element {
public static void main(String[] arg) {
int[] input = {6, 1, 5, 0, 0, 3, 8, 6, 4};
Stack<Integer> stack = new Stack<Integer>();
int k = 0;
int count = 0;
int last_index_value =input.length-1;
for (int i = 0; i < input.length; i++) {
if (input[i] != 0) {
int j = i + 1;
boolean flag = false;
while (j < input.length && input[i] != 0) {
if (input[j] > input[i]) {
if (stack.empty() || !flag) {
stack.push(input[j]);
flag = true;
j++;
} else if (stack.peek() > input[j]) {
stack.pop();
stack.push(input[j]);
flag = true;
j++;
} else {
j++;
}
} else {
j++;
}
}
if (flag) {
input[k] = stack.peek();
k++;
}
else {
input[k]=input[i];
k++;
}
}
else{
count +=1;
}
}
while(count>0){
input[last_index_value]=0;
last_index_value--;
count--;
}
for (int s :
input) {
System.out.println(s);
}
}
}
First shoveling the zeroes to the right would be one optimisation.
Possibly replacing with next closest greater element I have interpreted as next following element (as you seemed to do, as otherwise the last 4 might have become the overwritten 5).
static int[] f(int[] values) {
// In-situ (in-place) algorithm.
int n = 0; // The count of non-zero values.
for (int i = 0; i < values.length; ++i) {
if (values[i] != 0) {
values[n] = values[i];
++n;
}
}
// Zero the rest:
// (With a second array the remaining values from n upwards would
// already be zero.)
for (int i = n; i < values.length; ++i) {
values[i] = 0;
}
// {6, 1, 5, 0, 0, 3, 8, 6, 4} -> {6, 1, 5, 3, 8, 6, 4, [n] 0, 0}
// (First optimisation.) Now we only need to deal with n non-zero values.
// Search the next (A) closest greatest (B) number, when found substitute.
// Unoptimized:
for (int i = 0; i < n; ++i) {
int ithValue = values[i];
boolean hasClosest = false;
int closest = Integer.MAX_VALUE;
for (int j = i + 1; j < n; ++j) {
int jthValue = values[j];
if (jthValue > ithValue && (!hasClosest || jthValue < closest)) {
closest = jthValue;
hasClosest = true;
values[i] = jthValue;
}
}
}
// {8, 3, 6, 4, 8, 6, 4, 0, 0}
return values;
}
public static void main(String[] args) {
int[] input = {6, 1, 5, 0, 0, 3, 8, 6, 4};
System.out.println(Arrays.toString(f(input)));
}
The last piece is not well optimized.
An other interpretation of "closest greatest:"
int[] sorted = Arrays.copyOf(values, n);
Arrays.sort(sorted);
for (int i = 0; i < n; ++i) {
int j = Arrays.binarySearch(sorted, values[i] + 1);
if (j < 0) { // Not found 1 greater.
j = ~j; // Even greater.
}
if (j < n) {
values[i] = sorted[j];
}
}
// {8, 3, 6, 4, 8, 8, 5, 0, 0}
Sorting cost O(N log N), as does the loop O(N) times binary search O(log N).
So it is faster, costing memory. But that is comparible with you stack usage.
By the way, a cleaned up version of your code could have been put on CodeReview.

Directed Graph Shortest path source to destination Dijkstra

Here is my code to get the shortest path
static void shortestPath(int[][] adjacencyMatrix, int src, int dest) {
int n = adjacencyMatrix[0].length;
int[] shortest = new int[n];
boolean[] added = new boolean[n];
for (int v = 0; v < n;v++) {
shortest[v] = Integer.MAX_VALUE;
added[v] = false;
}
shortest[src] = 0;
int[] parents = new int[n];
parents[src] = NO_PARENT;
for (int i = 1; i < n; i++) {
int v1 = -1; //store temp data
int min = Integer.MAX_VALUE;
for (int v = 0; v < n; v++) {
if (!added[v] && shortest[v] < min) {
v1 = v;
min = shortest[v];
}
}
added[v1] = true; // ERROR HAPPENS HERE
for (int v = 0; v < n; v++) {
int dist = adjacencyMatrix[v1][v];
if (dist > 0 && ((min + dist) <shortest[v])){
parents[v] = v1;
shortest[v] = min + dist;
}
}
}
dists.add(shortest[dest]);
visitUtil(dest, parents);
}
static void visitUtil(int i,int[] parents) {
if (i == NO_PARENT)
return;
visitUtil(parents[i], parents);
edges.add(i);
}
My matrix is this
{ 0,10, 0, 0, 3 },
{0, 0, 5, 0, 1 },
{ 0, 0, 0, 7, 8 },
{ 0, 0, 0, 0, 2 },
{ 0, 0, 0, 0, 0 }
Here is my graph so you can see it.
I get a ArrayIndexOutOfBoundsException. For example, lets say I want to go from 2-4, in the graph below, you can see that the weight is 8, and they are directly attached.
How can I fix this?

Finding the Shortest Path in a 2D Integer Array Java

I am making a snake game where the snake crosses through a 2D int array as its terrain. The values stored in the 2D array represent the time in seconds it takes to cross.
For example,
int[][] MAP = {
{ 1, 1, 1, 2, 2 },
{ 1, 2, 2, 2, 2 },
{ 3, 2, 2, 3, 1 },
{ 1, 1, 3, 2, 1 },
{ 1, 1, 3, 2, 1 }
};
So going from map[0][0] to map[0][4] takes 1 + 1 + 2 + 2 seconds. How would I make an algorithm that would find the shortest possible path for a snake to travel from position map[startX][startY] to map[endX][endY]?
This isn't a homework assignment, I'm just making a game for fun and would like to learn how to do this.
This is one is kinda known problem when discussing "dynamic programming", and even resembles an old post.
Still, I didn't find a solution that also prints the shortest path, so:
public class FastestPathCalculator {
private final int[][] map;
public FastestPathCalculator(int[][] map) {
this.map=map;
}
public static void main(String[] args) {
int[][] map = new int[][]{
{1, 1, 1, 4, 2},
{1, 2, 5, 2, 2},
{3, 2, 2, 3, 1},
{1, 1, 3, 2, 1},
{3, 1, 3, 2, 1}
};
FastestPathCalculator c = new FastestPathCalculator(map);
boolean[] result = c.computeFastestPath(map);
c.printPath(result);
}
Here, the boolean array represents the steps taken from (0,0) to (4,4). A value of TRUE means the step is to the right, FALSE means go down.
In this example, the array has 8 cells.
public boolean[] computeFastestPath(int[][] map) {
int pathLength = map.length + map[0].length - 2;
boolean[] result = new boolean[pathLength];
int[][] mapOfMinimalSums = buildMapOfMinimalSums();
int x = map.length-1;
int y = map[0].length-1;
for (int i = pathLength - 1 ; i >= 0; i--) {
if (x == 0)
result[i] = true;
else if (y == 0)
result[i] = false;
else if (mapOfMinimalSums[x][y] == map[x][y] + mapOfMinimalSums[x][y-1]) {
result[i] = true;
y--;
}
else {
result[i] = false;
x--;
}
}
return result;
}
public void printPath(boolean[] result) {
String[][] newPath = new String[map.length][map[0].length];
int x = 0;
int y = 0;
newPath[x][y] = String.valueOf(map[x][y]);
for (int i = 0 ; i < result.length; i++) {
if (result[i]) {
y++;
} else {
x++;
}
newPath[x][y] = String.valueOf(map[x][y]);
}
for (int i = 0 ; i < map.length; i++) {
for (int j = 0 ; j < map[0].length; j++) {
if (newPath[i][j] == null) {
System.out.print(" , ");
} else {
System.out.print(newPath[i][j] + ", ");
}
}
System.out.println();
}
System.out.println();
}
private int[][] buildMapOfMinimalSums() {
int[][] mapOfSums = new int[map.length][map[0].length];
for (int i = 0 ; i < map.length; i++) {
for (int j = 0 ; j < map[0].length; j++) {
if (i == 0 && j == 0)
mapOfSums[i][j] = map[i][j];
else if (i == 0) {
mapOfSums[i][j] = mapOfSums[i][j - 1] + map[i][j];
}
else if (j == 0)
mapOfSums[i][j] = mapOfSums[i-1][j] + map[i][j];
else
mapOfSums[i][j] = Math.min(mapOfSums[i-1][j], mapOfSums[i][j-1]) + map[i][j];
}
}
return mapOfSums;
}
}

java.lang.IllegalArgumentException

I have the implementation of Branch and Bound I'am getting error in this function there is priority queue which will used further its getting IllegalArgumentException
//here is that line on which I'am getting this error
PriorityQueue<Node> pq = new PriorityQueue<>(0, comp);
import java.util.Comparator;
import java.util.PriorityQueue;
public class Node {
private int N = 3;
Node parent;
int[][] mat = new int[N][N];
int x, y;
int cost;
int level;
public void printMatrix(int[][] mat) {
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.print(mat[i][j]);
}
System.out.println();
}
}
public void newNode(int[][] mat, int x, int y, int newX, int newY, int level, Node parent) {
Node node = new Node();
node.parent = parent;
node.mat = mat;
node.mat[x][y] = node.mat[newX][newY];
node.cost = Integer.MAX_VALUE;
node.level = level;
node.x = newX;
node.y = newY;
}
int[] row = {1, 0, -1, 0};
int[] col = {0, -1, 0, 1};
public int calculateCost(int[][] initial, int[][] fin) {
int count = 0;
for (int i = 0; i < fin.length; i++) {
for (int j = 0; j < fin.length; j++) {
if(initial[i][j] != fin[i][j])
count++;
}
}
return count;
}
public int isSafe(int x, int y) {
if ((x >= 0 && x < N) && (y >= 0 && y < N))
return 1;
return 0;
}
public void printPath(Node root) {
if(root == null)
return;
printPath(root.parent);
printMatrix(root.mat);
System.out.println();
}
**// here I'am getting error in this function there is priority queue which will used further its getting IllegalArgumentException **
public void solve(int[][] initial, int x, int y, int[][] fin) {
Comparator<Node> comp = new Comparator<Node>() {
#Override
public int compare(Node lhs, Node rhs) {
if((lhs.cost + lhs.level) > (rhs.cost + rhs.level))
return 1;
return 0;
}
};
//here is that line on which im getting this error
PriorityQueue<Node> pq = new PriorityQueue<>(0, comp);
Node root = new Node();
root.newNode(initial, x, y, x, y, 0, null);
root.cost = calculateCost(initial, fin);
pq.add(root);
while(!pq.isEmpty()) {
Node min = pq.peek();
pq.remove();
if(min.cost == 0) {
printPath(min);
return;
}
for (int i = 0; i < 4; i++) {
if(isSafe(min.x + row[i], min.y + col[i]) == 1) {
Node child = new Node();
child.newNode(min.mat, min.x, min.y, min.x + row[i], min.y + col[i], min.level + 1, min);
child.cost = calculateCost(child.mat, fin);
pq.add(child);
}
}
}
}
public static void main(String[] args) {
int[][] initial =
{
{1, 2, 3},
{5, 6, 0},
{7, 8, 4}
};
int[][] fin =
{
{1, 2, 3},
{5, 0, 6},
{8, 7, 4}
};
int x = 1, y = 2;
Node newNode = new Node();
newNode.solve(initial, x, y, fin);
}
}
From the javadoc (emphasis is mine):
public PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
[...]
Throws:
IllegalArgumentException - if initialCapacity is less than 1

Java - Unexpected behavior of 2d Array

The following code i wrote to solve a sudoku. I am experiencing an unexpected behavior here. I am calling the displaySudokuBoard twice. one from inside sudokuFiller when i value becomes greater then 8(i am getting the solved sudoku array) and another call from main function(It return me the same array which was given as input).
Why i am getting different values of my array. what is wrong with the code
class SudokuSolver {
public int[][] sudokuBoard = {{2, 0, 0, 0, 0, 1, 0, 3, 8},
{0, 0, 0, 0, 0, 0, 0, 0, 5},
{0, 7, 0, 0, 0, 6, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 3},
{0, 9, 8, 1, 0, 0, 2, 5, 7},
{3, 1, 0, 0, 0, 0, 8, 0, 0},
{9, 0, 0, 8, 0, 0, 0, 2, 0},
{0, 5, 0, 0, 6, 9, 7, 8, 4},
{4, 0, 0, 2, 5, 0, 0, 0, 0}};
private boolean checkNumberExistInRow(int i, int cellVals) {
for(int j = 0; j < 9; j++) {
if(sudokuBoard[i][j] == cellVals) {
return false ;
}
}
return true;
}
private boolean checkNumberExistInColumn(int j, int cellVals) {
for(int i = 0; i < 9; i++) {
if(sudokuBoard[i][j] == cellVals) {
return false;
}
}
return true;
}
private boolean checkNumberExistInGrid(int i, int j, int cellVals) {
i = (i / 3) * 3 ;
j = (j / 3) * 3;
for(int k = 0; k < 3; k++) {
for(int s = 0; s < 3; s++) {
if(sudokuBoard[i+k][j+s] == cellVals) {
return false;
}
}
}
return true;
}
private void FillNext(int i, int j) {
if(j < 8 ) {
sudokuFiller(i, j+1);
} else {
sudokuFiller(i+1, 0);
}
}
public void sudokuFiller (int i, int j) {
int k = 0;
if(i > 8) {
displaySodukoBoard();
return;
}
if(sudokuBoard[i][j] != 0) {
FillNext(i, j);
}
else {
for(int cellVals = 1; cellVals <= 9; cellVals++) {
if((checkNumberExistInRow(i, cellVals)) && (checkNumberExistInColumn(j, cellVals)) && (checkNumberExistInGrid(i, j, cellVals))) {
this.sudokuBoard[i][j] = cellVals;
FillNext(i,j);
}
}
this.sudokuBoard[i][j] = 0;
}
}
public void displaySodukoBoard() {
for(int row = 0; row < 9; ++row) {
for(int col = 0; col < 9; ++col) {
if ((col == 3) || (col == 6)){
System.out.printf("\t");
}
System.out.printf("%d ",sudokuBoard[row][col]);
}
if ((row == 2) || (row == 5)){
System.out.printf("\n");
}
System.out.print("\n");
}
}
}
class FeedMeASudoku {
public static void main(String[] args) {
SudokuSolver mySudokuSolver = new SudokuSolver();
mySudokuSolver.sudokuFiller(0,0);
System.out.print("\n");
mySudokuSolver.displaySodukoBoard();
}
}
Here is the problem: this.sudokuBoard[i][j] = 0;.
At the end of a set-process, you reset the field to 0 (sudokuFiller(int i, int j), else-statement, last line).
EDIT: this solves a part of the problem. The first three rows are now correctly displayed. However, the recursion does break preemptively. Now you need to debug your code further.
I assume you are trying to show the board first and then display the result of the new board which is your solution. The calculation was fine, but the order of calls was wrong.
In your Main() call, switch the second and fourth lines:
SudokuSolver mySudokuSolver = new SudokuSolver();
mySudokuSolver.displaySodukoBoard();
System.out.print("\n");
mySudokuSolver.sudokuFiller(0,0);
Also, as others suggested, you should learn how to debug and look for suggestions from LINT. For instance, you have unused variable int k = 0;

Categories