Last active
July 2, 2017 12:31
-
-
Save KeenWarrior/a411a97187980e16fad06d8584068367 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.LinkedList; | |
import java.util.Queue; | |
public class ShortestPathCustom { | |
private static int[][] data; | |
private static int[][] weights; | |
private static int m, n; | |
private static Queue<Index> queue; | |
public static int findDistance(){ | |
m = data.length; | |
n = data[0].length; | |
weights = new int[m][n]; | |
for (int[] a: weights) { | |
Arrays.fill(a, Integer.MAX_VALUE); | |
} | |
queue = new LinkedList<>(); | |
weights[0][0] = 0; | |
queue.add(new Index(0, 0)); | |
while (queue.size() != 0 && !(queue.peek().getX() == n-1 && queue.peek().getY() == m-1)) { | |
Index index = queue.remove(); | |
int x = index.getX(); | |
int y = index.getY(); | |
int value = weights[x][y]; | |
process(value, x, y - 1); | |
process(value, x, y + 1); | |
process(value, x - 1, y - 1); | |
process(value, x - 1, y); | |
process(value, x - 1, y + 1); | |
process(value, x + 1, y - 1); | |
process(value, x + 1, y); | |
process(value, x + 1, y + 1); | |
} | |
return weights[m-1][n-1]; | |
} | |
private static void process(int value, int x, int y) { | |
display(); | |
if ( x < 0 || x >=m || y < 0 || y >= n){ | |
return; | |
} else { | |
if(data[x][y] == 1 && weights[x][y] > value+1){ | |
weights[x][y] = value+1; | |
queue.add(new Index(x, y)); | |
} | |
} | |
} | |
private static void display() { | |
for (int[] a: weights) { | |
for (int b: a) { | |
System.out.print(b+" "); | |
} | |
System.out.println(); | |
} | |
System.out.println("=============================="); | |
} | |
public static class Index{ | |
private int x, y; | |
public Index(int x, int y) { | |
this.x = x; | |
this.y = y; | |
} | |
public int getX() { | |
return x; | |
} | |
public int getY() { | |
return y; | |
} | |
} | |
public static void main(String[] args) { | |
int[][] data = {{1, 0, 1, 1, 1}, | |
{1, 0, 1, 0, 1}, | |
{1, 0, 1, 0, 1}, | |
{1, 1, 1, 0, 1}}; | |
ShortestPathCustom.data = data; | |
System.out.println(findDistance()); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment