I have a question in JAVA I can't solve no matter how long I try to think about the solution:
There's a matrix and I need to find the shortest path possible to get from Mat[0][0] to the bottom right of the matrix and I can only proceed to the adjacent square (no diagonals) if the number in it is bigger than the one I'm on right now.
For example:
0 1 2 3 4
0 { 5 13 2 5 2
1 58 24 32 3 24
2 2 7 33 1 7
3 45 40 37 24 70
4 47 34 12 25 2
5 52 56 68 76 100}
So a valid solution would be:
(0,0)->(0,1)->(1,1)->(2,1)->(2,2)->(2,3)->(3,1)->(3,0)->(0,4)->(0,5)->(5,1)->(5,2)->(5,3)->(5,4)
And the method will return 14 because that's the shortest possible path.
I have to use a recursive method only (no loops).
This is what I came up with so far but I don't know how to figure out which is the shortest one.
Public static int shortestPath(int[][]mat)
{
int length=0;
int i=0;
int j=0;
shortestPath(mat, length, i, j);
}
Private static int shortestPath(int[][]math, int length, int i, int j)
{
if((i==mat.length)||(j==mat[i].length))
return length;
if(shortestPath(mat, length, i+1, j) > shortestPath(mat, length, i, j))
return length +1;
if(shortestPath(mat, length, i, j+1) > shortestPath(mat, length, i, j))
return length +1;
if shortestPath(mat, length, i-1, j) > shortestPath(mat, length, i, j))
return length +1;
if shortestPath(mat, length, i, j-1) > shortestPath(mat, length, i, j))
return length +1;
}
I'm not sure if that's the way to do it, and if it is: how do I know which is the shortest way, because right now it would return all possible ways and will add them together (I think).
Also, I think I should add something about reaching the bottom right of the matrix.
The code shouldn't be too complicated.
im not sure if the approach of going to the next smallest value is the shortest, but anyway:
public class Pathfinder {
private int[][] matrix;
private int matrixLenghtI;
private int matrixLenghtJ;
public Pathfinder(int[][] matrix, int matrixLenghtI, int matrixLenghtJ) {
this.matrix = matrix;
this.matrixLenghtI = matrixLenghtI;
this.matrixLenghtJ = matrixLenghtJ;
}
public static void main(String[] args) {
int matrixLenghtI = 6;
int matrixLenghtJ = 5;
int[][] matrix1 = { { 3, 13, 15, 28, 30 }, { 40, 51, 52, 29, 30 }, { 28, 10, 53, 54, 54 },
{ 53, 12, 55, 53, 60 }, { 70, 62, 56, 20, 80 }, { 80, 81, 90, 95, 100 } };
int[][] matrix2 = { { 5, 13, 2, 5, 2 }, { 58, 24, 32, 3, 24 }, { 2, 7, 33, 1, 7 }, { 45, 40, 37, 24, 70 },
{ 47, 34, 12, 25, 2 }, { 52, 56, 68, 76, 100 } };
Pathfinder finder1 = new Pathfinder(matrix1, matrixLenghtI, matrixLenghtJ);
finder1.run();
Pathfinder finder2 = new Pathfinder(matrix2, matrixLenghtI, matrixLenghtJ);
finder2.run();
}
private void run() {
int i = 0;
int j = 0;
System.out.print("(" + i + "," + j + ")");
System.out.println("\nLength: " + find(i, j));
}
private int find(int i, int j) {
int value = matrix[i][j];
int[] next = { i, j };
int smallestNeighbour = 101;
if (i > 0 && matrix[i - 1][j] > value) {
smallestNeighbour = matrix[i - 1][j];
next[0] = i - 1;
next[1] = j;
}
if (j > 0 && matrix[i][j - 1] < smallestNeighbour && matrix[i][j - 1] > value) {
smallestNeighbour = matrix[i][j - 1];
next[0] = i;
next[1] = j - 1;
}
if (i < matrixLenghtI - 1 && matrix[i + 1][j] < smallestNeighbour && matrix[i + 1][j] > value) {
smallestNeighbour = matrix[i + 1][j];
next[0] = i + 1;
next[1] = j;
}
if (j < matrixLenghtJ - 1 && matrix[i][j + 1] < smallestNeighbour && matrix[i][j + 1] > value) {
smallestNeighbour = matrix[i][j + 1];
next[0] = i;
next[1] = j + 1;
}
System.out.print("->(" + next[0] + "," + next[1] + ")");
if (i == matrixLenghtI - 1 && j == matrixLenghtJ - 1)
return 1;
return find(next[0], next[1]) + 1;
}
}
Output:
(0,0)->(0,1)->(0,2)->(0,3)->(1,3)->(1,4)->(2,4)->(3,4)->(4,4)->(5,4)->(5,4)
Length: 10
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(3,1)->(3,0)->(4,0)->(5,0)->(5,1)->(5,2)->(5,3)->(5,4)->(5,4)
Length: 14
Position class:
/**
* Represents a position in the matrix.
*/
public class Position {
final private int x;
final private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public String toString() {
return "(" + x + ", " + y + ')';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position position = (Position) o;
if (x != position.x) return false;
return y == position.y;
}
#Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
Board class:
/**
* A board represents all of the locations in the matrix. It provides a simple interface to getting
* the value in a position, and tracking the height and width of the matrix.
*/
public class Board {
final int [][] board;
public Board(int[][] board) {
this.board = board;
}
final int positionValue(Position position) {
return this.board[position.getY()][position.getX()];
}
final int getWidth() {
return board[0].length;
}
final int getHeight() {
return board.length;
}
}
PathFinder class:
import java.util.ArrayList;
import java.util.List;
/**
* Find the shortest path from a starting point to ending point in a matrix, assuming you can
* only move to a position with a greater value than your current position.
*/
public class PathFinder {
final private Board board;
final private Position start;
final private Position end;
public PathFinder(Board board, int startX, int startY, int endX, int endY) {
this.board = board;
this.start = new Position(startX, startY);
this.end = new Position(endX, endY);
}
/**
* Gets the shortest path from the start to end positions. This method
* takes all of the paths, then determines which one is shortest and returns that.
*
* #return the shortest path from the start to end positions.
*/
public List<Position> shortestPath() {
List<List<Position>> allPaths = this.getAllPaths();
System.out.println("Paths found: " + allPaths.size());
List<Position> shortestPath = null;
for (List<Position> path : allPaths) {
if (shortestPath == null) {
shortestPath = path;
}
else if (shortestPath.size() > path.size()) {
shortestPath = path;
}
}
return shortestPath;
}
/**
* Convenience method for starting the getAllPaths process.
*
* #return all of the paths from the start to end positions
*/
private List<List<Position>> getAllPaths() {
List<List<Position>> paths = new ArrayList<List<Position>>();
return this.getAllPaths(paths, new ArrayList<Position>(), start);
}
/**
* Gets all of the paths from the start to end position. This is done recursively by visiting every
* position, while following the rules that you can only move to a position with a value greater
* than the position you're currently on. When reaching the end position, the path is added to
* the list of all found paths, which is returned.
*
* #param paths the current list of all found paths.
* #param path the current path
* #param position the current position
* #return all paths from the start to end positions
*/
private List<List<Position>> getAllPaths(List<List<Position>> paths, List<Position> path, Position position) {
path.add(position);
if (position.equals(end)) {
paths.add(path);
return paths;
}
//x+
if (position.getX() + 1 < board.getWidth()) {
Position xp = new Position(position.getX() + 1, position.getY());
if (board.positionValue(position) < board.positionValue(xp)) {
getAllPaths(paths, new ArrayList<Position>(path), xp);
}
}
//x-
if (position.getX() - 1 >= 0) {
Position xm = new Position(position.getX() - 1, position.getY());
if (board.positionValue(position) < board.positionValue(xm)) {
getAllPaths(paths, new ArrayList<Position>(path), xm);
}
}
//y+
if (position.getY() + 1 < board.getHeight()) {
Position yp = new Position(position.getX(), position.getY() + 1);
if (board.positionValue(position) < board.positionValue(yp)) {
getAllPaths(paths, new ArrayList<Position>(path), yp);
}
}
//y-
if (position.getY() - 1 >= 0) {
Position ym = new Position(position.getX(), position.getY() - 1);
if (board.positionValue(position) < board.positionValue(ym)) {
getAllPaths(paths, new ArrayList<Position>(path), ym);
}
}
return paths;
}
/**
* Run the example then print the results.
*
* #param args na
*/
public static void main(String[] args) {
int [][] array = {{5, 13, 2, 5, 2},
{14, 24, 32, 3, 24},
{15, 7, 33, 1, 7},
{45, 40, 37, 24, 70},
{47, 34, 12, 25, 2},
{52, 56, 68, 76, 100}
};
final Board board = new Board(array);
final Position end = new Position(board.getWidth()-1, board.getHeight() - 1);
final PathFinder pathFinder = new PathFinder(board, 0, 0, board.getWidth()-1, board.getHeight()-1);
final List<Position> path = pathFinder.shortestPath();
System.out.println("Shortest Path: ");
for (Position position : path) {
if (!position.equals(end)) {
System.out.print(position + " -> ");
}
else {
System.out.println(position);
}
}
System.out.println();
}
}
I really like this problem. Unfortunately I haven't worked in Java for many years, so this answer is pseudo-Java and you'll have to fix some of the syntax. Probably some of the function params should be references and not copies; you'll figure it out (update: I've added a TESTED version in python below).
// just a little thing to hold a set of coordinates
class Position
{
// not bothering with private / getters
public int x ;
public int y ;
public constructor (int x, int y)
{
this.x = x ;
this.y = y ;
}
}
class PathFinder
{
public void main (void)
{
// create a path with just the start position
start = new Position(0, 0) ;
path = new Vector() ;
path.add(start) ;
// create an empty path to contain the final shortest path
finalPath = new Vector() ;
findPath(path, finalPath) ;
print ("Shortest Path: ") ;
showPath (finalPath) ;
}
private void showPath (Vector path) {
// print out each position in the path
iter = path.iterator() ;
while (pos = iter.next()) {
print ("(%, %) ", pos.x, pos.y);
}
// print out the length of the path
print (" Length: %\n", path.size()) ;
}
// recursive function to find shortest path
private void findPath (Vector path, Vector finalPath)
{
// always display the current path (it should never be the same path twice)
showPath(path) ;
// where are we now?
here = path.lastElement() ;
// does the current path find the exit (position 4,5)?
if (here.x == 4 && here.y == 5) {
if (finalPath.size() == 0) {
//finalPath is empty, put the current path in finalPath
finalPath = path ;
} else {
// some other path found the exit already. Which path is shorter?
if (finalPath.size() > path.size()) {
finalPath = path ;
}
}
// either way, we're at the exit and this path goes no further
return ;
}
// path is not at exit; grope in all directions
// note the code duplication in this section is unavoidable
// because it may be necessary to start new paths in three
// directions from any given position
// If no new paths are available from the current position,
// no new calls to findPath() will happen and
// the recursion will collapse.
if (here.x > 0 && matrix[here.x-1][here.y] > matrix[here.x][here.y]) {
// we can move left
newPos = new Position(here.x-1, here.y) ;
newPath = path ;
newPath.add (newPos) ;
findPath(newPath, finalPath) ;
}
if (here.x < 4 && matrix[here.x+1][here.y] > matrix[here.x][here.y]) {
// we can move right
newPos = new Position(here.x+1, here.y) ;
newPath = path ;
newPath.add (newPos) ;
findPath(newPath, finalPath) ;
}
if (here.y > 0 && matrix[here.x][here.y-1] > matrix[here.x][here.y]) {
// we can move up
newPos = new Position(here.x, here.y-1) ;
newPath = path ;
newPath.add (newPos) ;
findPath(newPath, finalPath) ;
}
if (here.y < 5 && matrix[here.x][here.y+1] > matrix[here.x][here.y]) {
// we can move down
newPos = new Position(here.x, here.y+1) ;
newPath = path ;
newPath.add (newPos) ;
findPath(newPath, finalPath) ;
}
}
}
Here's a tested version of the same algorithm in python. (I noticed that using x, y as coordinates is kind of misleading. x is actually "vertical" and y is "horizontal" with the array indexed the way it is. I've set up a matrix with four paths to the exit and a couple of dead ends.)
import copy, sys
matrix = [
[5, 13, 17, 58, 2],
[17, 24, 32, 3, 24],
[23, 7, 33, 1, 7],
[45, 40, 37, 38, 70],
[47, 34, 12, 25, 2],
[52, 56, 68, 76, 100]]
def showPath(path):
for position in path:
sys.stdout.write("(" + str(position[0]) + ", " + str(position[1]) + "), ")
sys.stdout.write("\n\n")
sys.stdout.flush()
def findPath(path):
#showPath(path)
global finalPath
x = path[-1][0]
y = path[-1][1]
if x == 5 and y == 4:
showPath(path)
if len(finalPath) == 0 or len(finalPath) > len (path):
finalPath[:] = copy.deepcopy(path)
return
if x > 0 and matrix[x-1][y] > matrix[x][y]:
# we can move up
newPath = copy.deepcopy(path)
newPath.append([x-1, y])
findPath(newPath)
if x < 5 and matrix[x+1][y] > matrix[x][y]:
# we can move down
newPath = copy.deepcopy(path)
newPath.append([x+1, y])
findPath(newPath)
if y > 0 and matrix[x][y-1] > matrix[x][y]:
# we can move left
newPath = copy.deepcopy(path)
newPath.append([x, y-1])
findPath(newPath)
if y < 4 and matrix[x][y+1] > matrix[x][y]:
# we can move right
newPath = copy.deepcopy(path)
newPath.append([x, y+1])
findPath(newPath)
path = []
path.append([0, 0])
finalPath = []
findPath(path)
print "Shortest Path: " + str(len(finalPath)) + " steps.\n"
showPath(finalPath)
If you uncomment the first showPath() call in findPath() you can see every step and see where the dead ends get abandoned. If you only show paths that reach the exit, the output looks like:
(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
(0, 0), (1, 0), (1, 1), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (3, 2), (3, 1), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
Shortest Path: 10 steps.
(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4),
here you can build a tree to all possibilities and take then the shortest. There is a loop inside for tracing the result, but you can also get around that with some ugly ifs...
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class BetterPathfinder {
public class Comperator implements Comparator<Path> {
#Override
public int compare(Path o1, Path o2) {
return o1.getValue().compareTo(o2.getValue());
}
}
public class Path {
private Integer lenght;
TreeMap<Integer, String> trace = new TreeMap<>();
public Path(int lenght) {
this.lenght = lenght;
}
public Path(Path find, int i, int j) {
this.lenght = find.getValue() + 1;
this.trace.putAll(find.getTrace());
this.trace.put(lenght, "(" + i + "," + j + ")");
}
private Map<Integer, String> getTrace() {
return trace;
}
public Integer getValue() {
return lenght;
}
#Override
public String toString() {
String res = "end";
for (Entry<Integer, String> is : trace.entrySet()) {
res = is.getValue() + "->" + res;
}
return res;
}
}
private int[][] matrix;
private int matrixLenghtI;
private int matrixLenghtJ;
public BetterPathfinder(int[][] matrix, int matrixLenghtI, int matrixLenghtJ) {
this.matrix = matrix;
this.matrixLenghtI = matrixLenghtI;
this.matrixLenghtJ = matrixLenghtJ;
}
public static void main(String[] args) {
int matrixLenghtI = 6;
int matrixLenghtJ = 5;
int[][] matrix1 = { { 3, 13, 15, 28, 30 }, { 40, 51, 52, 29, 30 }, { 28, 10, 53, 54, 54 },
{ 53, 12, 55, 53, 60 }, { 70, 62, 56, 20, 80 }, { 80, 81, 90, 95, 100 } };
int[][] matrix2 = { { 5, 13, 2, 5, 2 }, { 58, 24, 32, 3, 24 }, { 2, 7, 33, 1, 7 }, { 45, 40, 37, 24, 70 },
{ 47, 34, 12, 25, 2 }, { 52, 56, 68, 76, 100 } };
BetterPathfinder finder1 = new BetterPathfinder(matrix1, matrixLenghtI, matrixLenghtJ);
finder1.run();
BetterPathfinder finder2 = new BetterPathfinder(matrix2, matrixLenghtI, matrixLenghtJ);
finder2.run();
}
private void run() {
int i = 0;
int j = 0;
System.out.println(new Path(find(i, j), i, j));
}
private Path find(int i, int j) {
int value = matrix[i][j];
int[] next = { i, j };
ArrayList<Path> test = new ArrayList<>();
if (i == matrixLenghtI - 1 && j == matrixLenghtJ - 1)
return new Path(1);
if (i > 0 && matrix[i - 1][j] > value) {
next[0] = i - 1;
next[1] = j;
test.add(new Path(find(next[0], next[1]), next[0], next[1]));
}
if (j > 0 && matrix[i][j - 1] > value) {
next[0] = i;
next[1] = j - 1;
test.add(new Path(find(next[0], next[1]), next[0], next[1]));
}
if (i < matrixLenghtI - 1 && matrix[i + 1][j] > value) {
next[0] = i + 1;
next[1] = j;
test.add(new Path(find(next[0], next[1]), next[0], next[1]));
}
if (j < matrixLenghtJ - 1 && matrix[i][j + 1] > value) {
next[0] = i;
next[1] = j + 1;
test.add(new Path(find(next[0], next[1]), next[0], next[1]));
}
if (test.isEmpty()) {
return new Path(100);
}
return Collections.min(test, new Comperator());
}
}
result:
(0,0)->(1,0)->(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)->end
(0,0)->(0,1)->(1,1)->(1,2)->(2,2)->(3,2)->(3,1)->(3,0)->(4,0)->(5,0)->(5,1)->(5,2)->(5,3)->(5,4)->end
You want a recursive strategy. A pretty easy, though expensive method, is to simply flood the board. Something like "Try every possible path and compute the distance".
You can do this recursively by imagining moving a pebble around.
public int shortestPath(Point src, Point dest) {
if (src.equals(dest)) {
return 0;
}
// You need to do some bound checks here
int left = shortestPath(new Point(src.x - 1, src.y), dest);
int right = shortestPath(new Point(src.x + 1, src.y), dest);
int up = shortestPath(new Point(src.x, src.y + 1), dest);
int down = shortestPath(new Point(src.x, src.y - 1), dest);
// Decide for the direction that has the shortest path
return min(left, right, up, down) + 1;
}
If you are interested in the path represented by the solution, you may trace the path while creating. For this you simply need to save for which direction min decided.
I needed to solve a similar task ages ago in my computer science studies. We needed to compute the shortest amount of moves a knight on a chess board needs for reaching a given destination. Maybe this also helps you: http://pastebin.com/0xwMcQgj
public class shortestPath{
public static int shortestPath(int[][] mat){
if(mat == null || mat.length == 0 || mat[0].length == 0)
return 0;
else {
int n = shortestPath(mat, 0, 0, 0);
return (n == mat.length*mat.length+1 ) ? 0 : n;
}
}
private static int shortestPath(int[][]mat, int row, int col,int prev){
if (!valid(mat,row,col) || !(mat[row][col] > prev)){
return mat.length*mat.length+1;
} else if(row == mat.length - 1 && col == mat[row].length - 1) {
return 1;
} else {
return minimum(shortestPath(mat,row-1,col, mat[row][col]),
shortestPath(mat,row+1,col, mat[row][col]),
shortestPath(mat,row,col-1, mat[row][col]),
shortestPath(mat,row,col+1, mat[row][col])) + 1;
}
}
private static boolean valid(int[][]mat,int row, int col){
if(row < 0 || col < 0 || col > mat[0].length-1 || row > mat.length-1)
return false;
else
return true;
}
private static int minimum(int x, int y, int t, int z){
int min1 = (x > y)? y : x;
int min2 = (t > z)? z : t;
return (min1 > min2)? min2 : min1;
}
public static void main(String[] args){
int maze[][] = {
{ 3, 13, 15, 28, 30},
{ 40, 51, 52, 29, 30},
{ 28, 10, 53, 54, 53},
{ 53, 12, 55, 53, 60},
{ 70, 62, 56, 20, 80},
{ 81, 81, 90, 95, 100}};
System.out.println(shortestPath(maze));
}
}
Here is how I solved it, note that in your example we should get 16
public static void main(String[] args)
{
int[][] mat =
{
{ 3, 13, 15, 28, 30 },
{ 40, 51, 52, 29, 30 },
{ 28, 10, 53, 54, 53 },
{ 53, 12, 55, 53, 60 },
{ 70, 62, 56, 20, 80 },
{ 80, 81, 90, 95, 100 }
};
System.out.println(shortestPath(mat)); // 10
int[][] mat1 =
{
{0, 1, 2, 3, 4 },
{0, 5, 13, 2, 5, 2},
{1, 58, 24, 32, 3, 24} ,
{2, 2 , 7, 33, 1, 7} ,
{3, 45, 40, 37, 24, 70},
{4, 47, 34, 12, 25, 2},
{5, 52, 56, 68, 76, 100}
};
System.out.println(shortestPath(mat1)); // 16
}
public static int shortestPath(int[][] mat)
{
return shortestPath(mat, 0, 0, mat[0][0] - 1, 0);
}
private static int shortestPath(int[][] mat, int row, int col, int prev, int counter)
{
if (row < 0 || row == mat.length || col < 0 || col == mat[row].length) // boundaries
return Integer.MAX_VALUE;
if (mat[row][col] <= prev || mat[row][col] == -999) // if the sequence is not ascending or if we have been in this cell before
return Integer.MAX_VALUE;
if (row == mat.length - 1 && col == mat[row].length - 1)
return counter + 1;
int temp = mat[row][col];
mat[row][col] = -999;
int up = shortestPath(mat, row - 1, col, temp, counter + 1); // go up and count
int down = shortestPath(mat, row + 1, col, temp, counter + 1);
int left = shortestPath(mat, row, col - 1, temp, counter + 1);
int right = shortestPath(mat, row, col + 1, temp, counter + 1);
mat[row][col] = temp;
return Math.min(Math.min(up, down), Math.min(left, right)); // get the min
}
I am coding Zombies infect people in a city whereas:
2: There is no person
1: Uninfected people
0: Zombies
Zombies will infect all normal people that are around Zombies.
Below is my Java program but I am getting the error: StackOverflowError.
public class InfectGame {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[][] = { { 1, 1, 1, 1, 2, 2, 2, 1, 1, 0 },
{ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 2, 1, 1, 2, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 0, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1, 1, 2, 1 },
{ 2, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 2, 2, 2, 1, 1, 1, 1, 1, 1, 2 }, };
int i = 0;
int j = 0;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
if (a[i][j] == 0) {
run_test(i, j, a, 0, 10);
}
}
}
i = 0;
j = 0;
for (i = 0; i < 10; i++) {
System.out.print("\n");
for (j = 0; j < 10; j++) {
System.out.print(a[i][j] + " ");
}
}
}
public static void run_test(int x, int y, int a[][], int v, int size) {
if ((x < 0) || (x >= size))
return;
if ((y < 0) || (y >= size))
return;
// System.out.print(a[x][y] + " ");
// a[x][y] = v;
if (a[x][y] != 2) {
a[x][y] = v;
if (x + 1 < size) {
run_test(x + 1, y, a, v, size);
}
if (x > 0) {
run_test(x - 1, y, a, v, size);
}
if (y + 1 < size) {
run_test(x, y + 1, a, v, size);
}
if (y > 0) {
run_test(x, y - 1, a, v, size);
}
}
}
}
Exception in thread "main" java.lang.StackOverflowError
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
at InfectGame.run_test(InfectGame.java:55)
at InfectGame.run_test(InfectGame.java:58)
........................................................
Recursion only works if you have terminating conditions.
You don't have them. Look at this part of your code:
if (x + 1 < size) {
run_test(x + 1, y, a, v, size);
}
if (x > 0) {
run_test(x - 1, y, a, v, size);
}
The first if statement will recurse until you've hit the end of the grid on the current line. At that point, it will go to the second if statement and recurse again, but one step back to the left. But on the next recursion, it will go one step to the right again, ad infinitum.
That's why you get the error - you never terminate your recursion.
Now that you explained that you are trying to do a flood fill, I can see which terminating condition you need:
if (a[x][y] != 2) {
Should be:
if (a[x][y] != 2 && a[x][y] != v) {
Otherwise you keep filling the same squares with zombies over and over again.
But thinking more about your problem of zombies, it is a bit different from an ordinary fill. In a fill, if a pixel already has the colour your want, you can stop the recursion.
For zombies that is not true for the first zombie - from this zombie it spreads out. So the first iteration should not check whether it is already a zombie, but any further iteration of the recursion should check, or else it doesn't terminate.
You can do it like this:
public static void run_test(int x, int y, int a[][], int v, int size, boolean first) {
if ((x < 0) || (x >= size))
return;
if ((y < 0) || (y >= size))
return;
if (a[x][y] != 2 && (first || a[x][y] != v)) {
a[x][y] = v;
if (x + 1 < size) {
run_test(x + 1, y, a, v, size, false);
}
if (x > 0) {
run_test(x - 1, y, a, v, size, false);
}
if (y + 1 < size) {
run_test(x, y + 1, a, v, size, false);
}
if (y > 0) {
run_test(x, y - 1, a, v, size, false);
}
}
}
And the invocation from the main method should read:
run_test(i, j, a, 0, 10, true);
You stuck here:
if (x + 1 < size) {
run_test(x + 1, y, a, v, size);
}
if (x > 0) {
run_test(x - 1, y, a, v, size);
}
Because x is always the first or second if- condition.
You should use better variable names. Use something that describes the variable instead of x, y, z.
This is my first time implementing Dijkstra's algorithm. Okay so here I have a simple 2D 9 by 9 array:
Starting point is 1 and we're trying to get to any green square. Red squares are walls or lava (whatever satisfies your imagination).
How do I implement this in Java?
Computer science is not my field hence I'm not a seasoned programmer so I might not know how to do some stack pushing, only loops and recursion :( please keep it easy as possible and bear with me!
Here's something similiar that should get you started. However, the solution presented below attempts to get to the bottom right corner. You can relax that condition to find the bottom row. You will also need to change the encoding slightly to have a unique value that represents this row.
public class MazeSolver {
final static int TRIED = 2;
final static int PATH = 3;
// #formatter:off
private static int[][] GRID = {
{ 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1 },
{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1 },
{ 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1 },
{ 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
};
// #formatter:off
public static void main(String[] args) {
MazeSolver maze = new MazeSolver(GRID);
boolean solved = maze.solve();
System.out.println("Solved: " + solved);
System.out.println(maze.toString());
}
private int[][] grid;
private int height;
private int width;
private int[][] map;
public MazeSolver(int[][] grid) {
this.grid = grid;
this.height = grid.length;
this.width = grid[0].length;
this.map = new int[height][width];
}
public boolean solve() {
return traverse(0,0);
}
private boolean traverse(int i, int j) {
if (!isValid(i,j)) {
return false;
}
if ( isEnd(i, j) ) {
map[i][j] = PATH;
return true;
} else {
map[i][j] = TRIED;
}
// North
if (traverse(i - 1, j)) {
map[i-1][j] = PATH;
return true;
}
// East
if (traverse(i, j + 1)) {
map[i][j + 1] = PATH;
return true;
}
// South
if (traverse(i + 1, j)) {
map[i + 1][j] = PATH;
return true;
}
// West
if (traverse(i, j - 1)) {
map[i][j - 1] = PATH;
return true;
}
return false;
}
private boolean isEnd(int i, int j) {
return i == height - 1 && j == width - 1;
}
private boolean isValid(int i, int j) {
if (inRange(i, j) && isOpen(i, j) && !isTried(i, j)) {
return true;
}
return false;
}
private boolean isOpen(int i, int j) {
return grid[i][j] == 1;
}
private boolean isTried(int i, int j) {
return map[i][j] == TRIED;
}
private boolean inRange(int i, int j) {
return inHeight(i) && inWidth(j);
}
private boolean inHeight(int i) {
return i >= 0 && i < height;
}
private boolean inWidth(int j) {
return j >= 0 && j < width;
}
public String toString() {
String s = "";
for (int[] row : map) {
s += Arrays.toString(row) + "\n";
}
return s;
}
}
I would suggest you start with writing down a method of applying dijkstras algorithm (assuming you know it in the first place) here in natural language and then start transforming it to your programming language.
The basic questions you will need to answer for that:
What are the nodes?
What are the connections?
What is the weight of each connection?
Once you did this you should be able to find a (probably not efficient) solution.
The optimal solution is indeed to use Dijkstra or AStar with a different finish condition. So you need to write if(targetNodes.contains(u)) break; instead of if(target == u) break;
(see wikipedia: If we are only interested in a shortest path between vertices source and target, we can terminate the search at line 13 if u = target.)
This is already implemented in my project called ... oh is this homework ;) ?
I have this code in C from this source:
#import <Foundation/Foundation.h>
#import "OpenGLCommon.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableString *result = [NSMutableString string];
static const Vertex3D vertices[]= {
{0, -0.525731, 0.850651}, // vertices[0]
{0.850651, 0, 0.525731}, // vertices[1]
{0.850651, 0, -0.525731}, // vertices[2]
{-0.850651, 0, -0.525731}, // vertices[3]
{-0.850651, 0, 0.525731}, // vertices[4]
{-0.525731, 0.850651, 0}, // vertices[5]
{0.525731, 0.850651, 0}, // vertices[6]
{0.525731, -0.850651, 0}, // vertices[7]
{-0.525731, -0.850651, 0}, // vertices[8]
{0, -0.525731, -0.850651}, // vertices[9]
{0, 0.525731, -0.850651}, // vertices[10]
{0, 0.525731, 0.850651} // vertices[11]
};
static const GLubyte icosahedronFaces[] = {
1, 2, 6,
1, 7, 2,
3, 4, 5,
4, 3, 8,
6, 5, 11,
5, 6, 10,
9, 10, 2,
10, 9, 3,
7, 8, 9,
8, 7, 0,
11, 0, 1,
0, 11, 4,
6, 2, 10,
1, 6, 11,
3, 5, 10,
5, 4, 11,
2, 7, 9,
7, 1, 0,
3, 9, 8,
4, 8, 0,
};
Vector3D *surfaceNormals = calloc(20, sizeof(Vector3D));
// Calculate the surface normal for each triangle
for (int i = 0; i < 20; i++)
{
Vertex3D vertex1 = vertices[icosahedronFaces[(i*3)]];
Vertex3D vertex2 = vertices[icosahedronFaces[(i*3)+1]];
Vertex3D vertex3 = vertices[icosahedronFaces[(i*3)+2]];
Triangle3D triangle = Triangle3DMake(vertex1, vertex2, vertex3);
Vector3D surfaceNormal = Triangle3DCalculateSurfaceNormal(triangle);
Vector3DNormalize(&surfaceNormal);
surfaceNormals[i] = surfaceNormal;
}
Vertex3D *normals = calloc(12, sizeof(Vertex3D));
[result appendString:#"static const Vector3D normals[] = {\n"];
for (int i = 0; i < 12; i++)
{
int faceCount = 0;
for (int j = 0; j < 20; j++)
{
BOOL contains = NO;
for (int k = 0; k < 3; k++)
{
if (icosahedronFaces[(j * 3) + k] == i)
contains = YES;
}
if (contains)
{
faceCount++;
normals[i] = Vector3DAdd(normals[i], surfaceNormals[j]);
}
}
normals[i].x /= (GLfloat)faceCount;
normals[i].y /= (GLfloat)faceCount;
normals[i].z /= (GLfloat)faceCount;
[result appendFormat:#"\t{%f, %f, %f},\n", normals[i].x, normals[i].y, normals[i].z];
}
[result appendString:#"};\n"];
NSLog(result);
[pool drain];
return 0;
}
Can some one point me to Java code that does the same thing as above? I would also need to modify it so that it works not just for isohadron but for any vertex array with associated index array.
This works for any triangle based mesh.
for(int i = 0; i < indices.Length; i += 3)
{
Vector3 v0 = vertices[indicies[i]].Position;
Vector3 v1 = vertices[indicies[i+1]].Position;
Vector3 v2 = vertices[indicies[i+2]].Position;
Vector3 normal = Vector3.Normalize(Vector3.Cross(v2 - v0, v1 - v0));
vertices[indicies[i]].Normal += normal;
vertices[indicies[i+1]].Normal += normal;
vertices[indicies[i+2]].Normal += normal;
}
for(int i = 0; i < vertices.Length; i++)
{
vertices[i].Normal = Vector3.Normalize(vertices[i].Normal);
}
Heres a stripped down version of the Vector3 struct
public struct Vector3
{
float X, Y, Z;
public Vector3(float x, float y, float z)
{
X = x; Y = y; Z = z;
}
public static Vector3 Cross(Vector3 v1, Vector3 v2)
{
Vector3 result;
result.X = (v1.Y * v2.Z) - (v1.Z * v2.Y);
result.Y = (v1.Z * v2.X) - (v1.X * v2.Z);
result.Z = (v1.X * v2.Y) - (v1.Y * v2.X);
return result;
}
public static Vector3 Normalize(Vector3 v1)
{
float length = v1.X * v1.X + v1.Y * v1.Y + v1.Z * v1.Z;
length = Math.Sqrt(length);
v1.X /= length; v1.Y /= length; v1.Z /= length;
}
}
I hope that helps.