How to do dijkstra's algorithm on a grid matrix - java

So I have a gird that can be any given size (i.e. matrix or 2d array). Each element contains a value and simply I need to find the shortest path. However, the problem I am having is trying to represent this grid as a graph or adj matrix or what ever you are meant to do. For example this is my code:
public int shortestPath (int[][] matrix, int sr, int sc, int dr, int dc)
{
int p = matrix.length * matrix[0].length;
int[] distances = new int[p];
boolean[] visited = new boolean[p]; //I think all are set to false by default
for (int i = 0; i < p; i++)
{
distances[i] = Integer.MAX_VALUE;
}
PriorityQueue<Node> pq = new Priority<>(); // a Node holds the int row, int col and the distance from source cell. It also orders by distances, so therefore a comparable was created to change natural order.
pq.add(new Node(sr,sc,0);
distances[(sr * matrix[0].length) + sc] = 0;
visited[(sr * matrix[0].length) + sc] = true;
while(!pq.isEmpty())
{
Node n = pq.poll();
int row = n.getRow();
int col = n.getColumn();
int dist = n.getDistance();
//Now here with a normal graph I would search neighbours via a for loop and find in the adj list where an element = 1 and is not visited. This is where I am stuck
}
}
So obviously with a grid, I will need to find neighbours of left/right/up/down (not doing diagonals). Thus, I need to take into account boundaries. How can a create an Adj matrix or what is the correct way to start searching neighbours for a grid like this?
I am having bad luck with this today because most examples show in graph form to adj matrix and not from grid form to adj matrix.

There's a trick for grid graphs:
lets say {x,y} denotes difference between 2 neighbour cells
You know neighbours will be in {0,-1}, {0,1}, {1,0} or {-1,0} (assuming no diagonal moves), or those cells will be out of bounds
Save arrays of those differences:
int differenceX[] = {0,0,1,-1};
int differenceY[] = {-1,1,0,0};
Now you can use for loop for neighbours:
for(int i=0; i<4; i++)
{
int neighRow = row + differenceY[i];
int neighCol = col + differenceX[i];
if(min(neighRow, neighCol) >= 0 && neighRow < matrix.length && neighCol < matrix[0].length){
//process node
}
}

Related

multiply diagonal values of a matrix in java

I want to multiply 2 diagonals of a Matrix. But i am not able to get the diagonals of matrix. like in given code two diagonals are d1=5*5*9. and d2=3*5*7 then i will use d1 and d2 values for further process.
How to do it.
Note: matrix size can be different like here its 3x3 but it can be 5x5
private static int diagonalMultiply(int [][]arr1){
int[][] arr= {
{5,2,3},
{4,5,6},
{7,8,9}
};
for ( int x = 0; x < arr.length; x++) //stepping along the x axis again.
{
for ( int y = 0; y < arr[x].length; y++) // stepping along the y axis.
{
System.out.print(arr[x][y]+" ");
}
}
return 0;
}
A diagonal of an N×N matrix has N elements. A pair of nested loops, each going from 0 to N-1, cover N2 elements. This means that you need one loop, not two.
Both diagonals can be retrieved in a single loop. Indexes of the descending diagonal are (i, i), while indexes of the ascending one are (N-i-1, i):
int N = arr.length;
for ( int i = 0; i < N ; i++) {
System.out.println(arr[i][i]+" "+arr[N-i-1][i]);
}
Demo.

Get edge with maximum weight to every node in MST using DFS

I have a minimum spanning tree and I am using DFS to traverse it where the datastructure of my graph is an adjancancy list. I want to get the edge with the maximum weight to every node from the source and store it in an array, this is what I have so far:
void recDFS(int currVertex, int source, int[] visited, int maxWeight){
visited[currVertex] = 1;
Vector<IntegerPair> neighbours = MSTAdjList.get(currVertex);
for(int j = 0; j < neighbours.size(); j++){
int neighbourWeight = neighbours.get(j)._second // get weight of neighbour
int neighbourIndex = neighbours.get(j)._first; // get index of neighbour
if (neighbourWeight > maxWeight)
maxWeight = neighbourWeight;
bigArrayWithValues[source][neighbourIndex] = maxWeight; // Store each value
recDFS(neighbourIndex, source, visited, maxWeight); // Call next neighbour
}
}
This won't work because when the recursion breaks, the value of maxWeight will still have the "old" value, while I want the edge with max weight to each node from the source that is fixed.. Any help would be appreciated.

In a NxN matrix, what algorithm finds the shortest path between two nodes?

Being new to algorithms and having searched all over the web, including some answers on stackoverflow, I still find myself asking how I find the distance between those nodes in a simple matrix.
First of all, the simple matrix:
public class MatrixRoutes {
int[][] position; // matrix
int size;
MatrixRoutes(int dimentions) {
posicion = new int[dimentions][dimentions];
size= dimensiones;
}
}
I set the size of the matrix with a simple
MatrixRoutes r = new MatrixRoutes(5);
Cool! I have my empty grid!
Populating it with the most simple of data, distances:
r.position[0][1] = 1;
r.position[1][1] = 0;
r.position[0][2] = 2;
r.position[2][2] = 0;
r.position[0][3] = 3;
r.position[3][3] = 0;
r.position[0][4] = 4;
r.position[4][4] = 0;
r.position[0][5] = 5;
r.position[5][5] = 0;
There's my test distance matrix, all ready to be tested.
Alright, got my nodes with distances. Now it's a matter of finding the shortest distance. I've been reading about different algorithms and their implementations with Java.
I've wanted to implement Dijkstra's algorithm, but it seems to only accept one starting number, used as a distance variable? That's not what I need when I need the distance between two variables.
Here's my attempt at implementing the algorithm:
private static int buscarRutaMasRapida(MatrixRoutes g, int nodeOrigin, int nodeDestiny)
{
int[] found = new int[g.position.length];
boolean[] visitedNode = new boolean[g.position.length];
int max = 999;
for (int i = 0; i < g.position.length; i++)
{
mejor[i] = max;
visitedNode [i] = false;
}
found[nodeOrigin+ nodeDestiny] = nodeOrigin + nodeDestiny;
for(int i = 0; i < g.position.length; i++)
{
int min = max;
int nodoNow = nodeOrigin;
for (int j = 0; j < g.position.length; j++)
{
if (!visitedNode [j] && found [j] < min)
{
nodoNow = j;
min = found [j];
}
}
visitedNode [nodoNow ] = true;
for (int j = 0; j < g.position.length; j++)
{
if (g.position[nodoNow ][j] < max && found[nodoNow ] + g.position[nodoNow ][j] < found [j])
{
found[j] = found [nodoNow ] + g.position[nodoNow ][j];
}
}
}
return found [g.position.length - 2];
}
All I'm asking is someone who would know of an algorithm which would find the shortest distance between two nodes in either a normal adjacency matrix or distance matrix.
Dijkstra's is the (my) preferred route. It takes in one node and finds the shortest path to all other nodes. Usually for distance between two nodes one would create a check inside Dijkstra's to return when the desired "end" node is reached.
In fact, Wikipedia has very nice psuedocode for you to use.
So for instance in the first step of Dijkstra's, you need to find the distance from the origin point S, you would look at all distances from S to other nodes and put this into your priority queue:
queue.add(position[S][x]); //Do this for all x adjacent to S
If you need to store the distance between each point then repeated use of Dijstraka's algorithm is inefficient if the adjacency graph is dense.
Instead you want the Floyd-Warshall algorithm.
From the wikipedia page, Dijstraka's will have a running time of O(V E log V ) while Floyd-Warshall will be O(V^3). In a connected graph E is between V (singly connected) and V^2 (each node connected to every other node), so the best will really depend on your data.

Rewrite code using a linked list instead an a 2D array in java

I need to rewrite this code that uses a 2D array using a singly linked list. I thought I could just step through the list in the same way that this code steps through the matrix but it doesn't work and stops when trying to read a 2x2 array. Here is the original code with the array version:
Input looks likes this, the order is listed above each matrix:
1
5
2
2 3
5 9
public class Determinant {
public static int calculate(LinkedList matrix, int order) {
int det = 0;
int z = 0;
int new_order= 0;
int rows = 0;
int a = 0;
if (matrix.size() == 1) {
a = (int)matrix.get(1);
return a;
} else {
for (int i = 0; i < order; i++){// minor matrix is one order less than matrix
LinkedList minor = new LinkedList();
while (rows < order) {
//build the minor matrix, ignoring the first row
for (int j = 1; j < order; j++) {
if (matrix.get(z)!= null) {
int y = z + order;
minor.add(matrix.get(y));
}z++;
}rows++;
}// determinant calculated with recursive call
new_order = order-1;
a = (int) matrix.get(i);
det += a*Math.pow(-1,i)*calculate(minor, new_order);
}
}return det;
}
I can at least get it to run when I take the recursive part out, but when I put it back it it gets stuck on the 2x2 matrix. I get this error: Exception in thread "main" java.lang.NullPointerException
at listdeterminant.Matrix.calculat

Best/Fastest way to iterate through all sub-matrices of a NxN matrix

I have a square board (NxN matrix). Each square (cell) has a certain points associated to it. My goal is to find the largest sub-matrix which has the highest summation of points. I started off with trying to find all the sub-matrices and their weights. But I am stuck on how to go about doing it.
I thought I could have a HashMap<String,Integer> which stores the initial row,column and the size of the sub matrix. The code should look something like this:
int [][] mat = new int[10][10];
void countSubMatrix()
{
for(int i = 0; i<mat.length; i++)
{
for(int j = 0; j<mat[i].length; j++)
{
storeSubMatrix(i,j);
}
}
}
void storeSubMatrix(int x, int y)
{
int size = 0;
int tempX = x;
int tempY = y;
while(tempX < board.length && tempY < board[x].length)
{
map.put(x.toString() + "," + y.toString(),size+1);
tempX++;
tempY++;
}
}
But I don't know if this is the right way to do it. Any thoughts?
Largest submatrix ,i.e, it can also be a rectangle, then this might be of help to you. Using kadane's algorithm for matrix it can be done in O(n^3).

Categories

Resources