Inconsistent results in BFS in Java - java

This code works fine when the first creation of a new maze object. However when the BFS is complete and the game is played again( by giving the user the option to play again) the algorithm does not work as effectively. The end goal is still met however x and y coordinates are added to the array that are not part of the shortest path. I have never seen my first run ever complete the search incorrectly, however subsequent instances do. It seems as if every time the new maze object is created the maze is left affected by the previous instance. Any input?
public class Maze {
public static List<Integer> fx;
public static List<Integer> fy;
public static int listSize;
public static Point p;
public Maze(int x, int y) {
p = getPathBFS(x, y);
fx = new ArrayList<>();
fy = new ArrayList<>();
addPoint();
System.out.print("next");
}
private static class Point {
int x;
int y;
Point parent;
public Point(int x, int y, Point parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent() {
return this.parent;
}
}
public static Queue<Point> q = new LinkedList<>();
public static Point getPathBFS(int x, int y) {
q.add(new Point(x, y, null));
while (!q.isEmpty()) {
Point p = q.remove();
if (Level.cells[p.x][p.y] == 9) {
return p;
}
if (isFree(p.x + 1, p.y)) {
Level.cells[p.x][p.y] = 2;
Point nextP = new Point(p.x + 1, p.y, p);
q.add(nextP);
}
if (isFree(p.x - 1, p.y)) {
Level.cells[p.x][p.y] = 2;
Point nextP = new Point(p.x - 1, p.y, p);
q.add(nextP);
}
if (isFree(p.x, p.y + 1)) {
Level.cells[p.x][p.y] = 2;
Point nextP = new Point(p.x, p.y + 1, p);
q.add(nextP);
}
if (isFree(p.x, p.y - 1)) {
Level.cells[p.x][p.y] = 2;
Point nextP = new Point(p.x, p.y - 1, p);
q.add(nextP);
}
}
return null;
}
public static boolean isFree(int x, int y) {
if ((x >= 0 && x < Level.cells.length) && (y >= 0 && y < Level.cells[x].length) && (Level.cells[x][y] == 0 || Level.cells[x][y] == 9)) {
return true;
}
return false;
}
public static void addPoint() {
while ((p != null)) {
System.out.println("x is " + p.x + " - y is " + p.y);
fy.add(p.x);
fx.add(p.y);
p = p.getParent();
}
}
public static int getListSize() {
listSize = fx.size();
return listSize;
}
}

It seems as if every time the new maze object is created the maze is
left affected by the previous instance
Yes, exactly. All of your fields are declared as static. Static fields are common across all instances, not just one. You can remove the static keyword in all (or almost all) instances.
public static List<Integer> fx;
public static List<Integer> fy;
public static int listSize;
public static Point p;
It looks like your Level class is suffering from the same problems:
Level.cells.length
I'd look into what 'static' actually means because it seems like you're using it without really understanding it.

Related

How to stop the normal force from being too small on a 2D rigidbody? (Java 2D)

I am trying to create a 2D game engine in Java with LWJGL 3. For now the objects are only rectangles with box colliders. For the collision detection I change the edge of the rectangles in to lines with the y = ax + b structure. One of the rectangles has a rigidbody component, that gives it the ability to move and interact with environment. The idea for now is to give the rigidbody a force at the start, gravity turned off, no friction, and a perfect bounce (bounciness=1). It all works very well, till it hits a rectangle with no vertical and horizontal edges. I found out that if the non-rigidbody objects are rotated by an angle other than 90 or 180 degrees the normal force is wrong (too small), how wrong depends on the rotation. The rotation of the rigidbody doesn't contribute to the problem.
Vector2 rotSurface = new Vector2(-collision.surface.ToVector().y, collision.surface.ToVector().x).getNormalized();
System.out.println("Angle: "+Physics.Angle(rotSurface, rb.force));
Vector2 normalForce = rotSurface.multiplyBy(rotSurface.multiplyBy(rb.force).getMagnitude());
rb.force = rb.force.add(normalForce).multiplyBy(1f - rb.friction).add(normalForce.multiplyBy(rb.bounciness));
System.out.println("Angle: "+Physics.Angle(rotSurface, rb.force));
System.out.println("===");
Am I doing something wrong here with calculating the new rigidbody force or the normal force itself? If you need more information to help me solve this problem please ask.
Classes that I use in the code above:
public class Collision {
Collider collider;
ArrayList<Vector2> contactPoints = new ArrayList<Vector2>();
Vector2 center = Vector2.zero;
Line surface;
public Collision(Collider collider, ArrayList<Vector2> contactPoints, Line surface) {
this.collider = collider;
this.contactPoints = contactPoints;
for(int i = 0; i < contactPoints.size(); i++) {
center = contactPoints.get(i).add(center).divideBy(2);
}
this.surface = surface;
}
}
class Line {
Vector2 begin, eind;
public float rc = 0;
public float b = 0;
public float x, y;
public boolean vertical = false;
public boolean horizontal = false;
public Line(Vector2 begin, Vector2 eind) {
this.begin = begin;
this.eind = eind;
if(begin.y == eind.y) {
this.y = begin.y;
this.horizontal = true;
}
else if(begin.x == eind.x){
this.x = begin.x;
this.vertical = true;
} else {
this.rc = (eind.y - begin.y) / (eind.x - begin.x);
this.b = GetB(rc, begin);
}
}
public float GetB(float rc, Vector2 punt) {
return punt.y - (rc * punt.x);
}
public Vector2 GetIntersection(Line l2) {
float x_ = rc - l2.rc;
if(vertical) {
x_ = x;
if(l2.horizontal) {
return new Vector2(x, l2.y);
}
else if(!l2.vertical){
//System.out.println("gert");
return new Vector2(x, l2.rc * x + l2.b);
}
} else if(horizontal) {
if(l2.vertical) {
return new Vector2(l2.x, y);
} else if(!l2.horizontal) {
return new Vector2((y-l2.b) / l2.rc, y);
}
} else {
if(l2.vertical) {
return new Vector2(l2.x, rc * l2.x + b);
} else if(l2.horizontal) {
return new Vector2((l2.y - b) / rc, l2.y);
}
}
if(x_ == 0) {
return null;
}
float getal = l2.b - b;
x_ = getal / x_;
float y_ = rc * x_ + b;
return new Vector2(x_, y_);
}
public Vector2 ToVector() {
return eind.substract(begin);
}
public float GetDisTo(Vector2 point) {
Vector2 point1 = begin.add(eind).divideBy(2);
return (float) Math.sqrt(Math.pow(point1.x - point.x, 2) + Math.pow(point1.y - point.y, 2));
}
public boolean Overlaps(Line line) {
if(horizontal && y == line.y) {
if(((line.begin.x > begin.x && line.begin.x < eind.x) || (line.eind.x > begin.x && line.eind.x < eind.x)) ||
((begin.x > line.begin.x && begin.x < line.eind.x) || (line.eind.x > line.begin.x && eind.x < line.eind.x)))
return true;
} else if(vertical && x == line.x) {
//return true;
}
return false;
}
}
class Vector2 {
float x, y;
public static Vector2 zero = new Vector2(0, 0);
public Vector2(float x, float y) {
this.x = x;
this.y = y;
}
public Vector2 multiplyBy(Vector2 vector) {
return new Vector2(x * vector.x, y * vector.y);
}
public Vector2 multiplyBy(float getal) {
return new Vector2(x * getal, y * getal);
}
public Vector2 divideBy(Vector2 vector) {
return new Vector2(x / vector.x, y / vector.y);
}
public Vector2 divideBy(float getal) {
return new Vector2(x / getal, y / getal);
}
public Vector2 add(Vector2 vector) {
return new Vector2(x + vector.x, y + vector.y);
}
public Vector2 substract(Vector2 vector) {
return new Vector2(x - vector.x, y - vector.y);
}
public float getMagnitude() {
return (float)Math.sqrt(x*x + y*y);
}
public Vector2 getNormalized() {
return divideBy(getMagnitude());
}
}
Fixed it by using a sinus.
I replaced
Vector2 normalForce = rotSurface.multiplyBy(rotSurface.multiplyBy(rb.force).getMagnitude());
with
Vector2 normalForce = rotSurface.multiplyBy((float)Math.sin(Math.toRadians((double) (90f - Physics.Angle(rotSurface, force)))) * force.getMagnitude());

Printing and comparing array data in java

I recently started learning Java and I'm having some trouble understanding how to make arrays to work the way I want them to.
Here I have an assignment of creating a polygon class with different methods inside.
Basically the class represents a convex polygon in a plane.
The array receives user input that consists of x and y coordinates and places them inside. (max number of vertices is 10).
There are some functions that I have no idea how to do and I would really appreciate some help with.
Point Class - which is used to get coordinates
public class Point {
private double _x;
private double _y;
public Point() {
this._x = 0.0D;
this._y = 0.0D;
}
public Point(double x, double y) {
this._x = x;
this._y = y;
}
public Point(Point other) {
this._x = other._x;
this._y = other._y;
}
public double getX() {
return this._x;
}
public double getY() {
return this._y;
}
public void setX(double x) {
if (x >= 0.0D)
this._x = x;
}
public void setY(double y) {
if (y >= 0.0D)
this._y = y;
}
public boolean isAbove(Point other) {
return (this._y > other._y);
}
public boolean isUnder(Point other) {
return other.isAbove(this);
}
public boolean isLeft(Point other) {
return (this._x < other._x);
}
public boolean isRight(Point other) {
return other.isLeft(this);
}
public double distance(Point other) {
double distance = Math.sqrt(Math.pow(this._x - other._x, 2.0D) + Math.pow(this._y - other._y, 2.0D));
return distance;
}
public void move(double dx, double dy) {
double x = this._x + dx;
double y = this._y + dy;
if (x >= 0.0D && y >= 0.0D) {
this._x = x;
this._y = y;
}
}
public boolean equals(Point other) {
return (this._x == other._x && this._y == other._y);
}
public String toString() {
return "(" + this._x + "," + this._y + ")";
}
}
Polygon Class - main class im working on
/**
* Write a description of class Polygon here.
*
* #author [REDACTED]
* #version (Ver 1.0)
*/
public class Polygon {
private Point[] _vertices;
private int _noOfVertices;
public Polygon() {
_vertices = (Point[]) new Point[10];
_noOfVertices = 0;
}
public Polygon(Point[] arr) {
_vertices = (Point[]) new Point[10];
_noOfVertices = 0;
if (arr.length > 10) {
return;
}
// for (Point P : arr)
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
_vertices[i] = arr[i];
_noOfVertices++;
}
}
}
public boolean addVertex(double x, double y) {
if (_noOfVertices >= 10)
return false;
Point p = new Point(x, y);
_vertices[_noOfVertices] = p;
_noOfVertices++;
return true;
}
public Point highestVertex() {
for (int i = 0; i < _noOfVertices; i++) {
}
}
public String toString() {
}
public double calcPerimeter() {
for (int i = 0; i < arr.length; i++) {
}
}
public double caclArea() {
Point ppp = _vertices[zzz]
}
public boolean isBigger(Polygon other) {
}
public int findVertex(Point p) {
for (int i = 0; i < _noOfVertices; i++) {
if (p.equals(_vertices[i])) {
return i;
}
}
return -1;
}
public Point getNextVertex(Point p) {
for (int i = 0; i < _noOfVertices; i++) {
if (p.equals(_vertices[i])) {
if (i == _noOfVertices - 1) {
return new Point(_vertices[0]);
}
return new Point(_vertices[i + 1]);
}
}
return null;
}
public Polygon getBoundingBox() {
}
}
I have no idea how to do these functions:
Line 44: public Point highestVertex() {} - returns a copy of the highest point in the polygon. If there is more than one vertice at the same Y - the method will return the first one it encountered (with the said Y) If there are no vertices aka the array is empty it will return null.
Line 52: public String toString() {} - method that returns a string of points representing the polygon. The string should be in the following format:
The polygon has 5 vertices:
((2.0,1.0),(5.0,0.0),(7.0,5.0),(4.0,6.0),(1.0,4,0))
If there are no vertices the method will return a string in the following format:
The polygon has 0 vertices.
English is not my first language so I apologize for any grammar mistakes in advance.
First, it's not really the best to ask homework questions here, this is a concept that you should learn.
In highestVertex(), they outline the 3 cases for you:
1st case: If point-y is equal to another point-y, return the first vertex that has point-y.
2nd case: if arr has no elements return null.
3rd case: in loop, check each element's y value in the array and compare it to the biggest y so far.
Use this line before your loop:
int max = Integer.MIN_VALUE;
Inside loop:
if (arr[i] > max) max = arr[i]
For toString(), again loop throughout the array, and add each point to a tracker string that you will return.
String str = "";
loop
str += arr[i].toString() + ",";
This works except you need to loop until arr's second to last element, as you will have an extraneous comma after the last point.

BFS issues return value is always null

I am working on this algorithm and cant figure out why I am always getting a null return. The code adds to two arrays fx, fy it collects the x and y positions that will complete the maze with the shortest path. The issue is that nothing is being added to the array. Any suggestions?
public class Maze {
public List<Integer> fx;
public List<Integer> fy;
public int listSize;
public Point p;
public int[][] cells;
public Maze(int x, int y, int[][] cells) {
p = getPathBFS(x, y, cells);
this.cells = cells;
fx = new ArrayList<>();
fy = new ArrayList<>();
addPoint();
}
private static class Point {
int x;
int y;
Point parent;
public Point(int x, int y, Point parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent() {
return this.parent;
}
}
public static Queue<Point> q = new LinkedList<>();
public Point getPathBFS(int x, int y, int[][] cells) {
q.add(new Point(x, y, null));
while (!q.isEmpty()) {
Point p = q.remove();
if (cells[p.x][p.y] == 9) {
return p;
}
if (isFree(p.x + 1, p.y, cells.length, cells)) {
cells[p.x][p.y] = 2;
Point nextP = new Point(p.x + 1, p.y, p);
q.add(nextP);
}
if (isFree(p.x - 1, p.y, cells.length, cells)) {
cells[p.x][p.y] = 2;
Point nextP = new Point(p.x - 1, p.y, p);
q.add(nextP);
}
if (isFree(p.x, p.y + 1, cells.length, cells)) {
cells[p.x][p.y] = 2;
Point nextP = new Point(p.x, p.y + 1, p);
q.add(nextP);
}
if (isFree(p.x, p.y - 1, cells.length, cells)) {
cells[p.x][p.y] = 2;
Point nextP = new Point(p.x, p.y - 1, p);
q.add(nextP);
}
}
return null;
}
public static boolean isFree(int x, int y, int cellLength, int[][] cells) {
if ((x >= 0 && x < cellLength) && (y >= 0 && y < cells[x].length) && (cells[x][y] == 0 || cells[x][y] == 9)) {
return true;
}
return false;
}
public synchronized void addPoint() {
System.out.println(p);
while ((p != null)) {
System.out.println("x is " + p.x + " - y is " + p.y);
fy.add(p.x);
fx.add(p.y);
p = p.getParent();
}
}
int getListSize() {
listSize = fx.size() - 1;
return listSize;
}
}

Java populating a 3D linked list with recursion

I'm getting a stack overflow while trying to populate my 3D linked list. I don't understand why it's not stopping at the specified bounds, it just runs forever. It's probably a simple error, i just don't understand.
EDIT: Okay I have now updated the code and removed that silly mistake, however it's still not operating exactly as intended. It does seem to be generating the 10x10x10 list, however its running infinitely. Initialized with (10, 10, 10), it should create 10000 objects and stop. I'm just trying to create a list to represent a 3d coordinate plane and each integer coordinate is one node, accessible by direction pointer north, south, east, west, up, or down.
Any help appreciated
public class Main {
public static void main(String[] args) {
NodeController3D con = new NodeController3D(6,6, 6);
}
}
public class Node3D {
// public Node3D(Node3D... nodes) {
// if (nodes.length != 5) {
// throw new RuntimeException();
// }
// this.nodes = nodes;
// }
public Node3D[] nodes;
public int x, y, z;
public Node3D north() {
return nodes[0];
}
public Node3D south() {
return nodes[1];
}
public Node3D east() {
return nodes[2];
}
public Node3D west() {
return nodes[3];
}
public Node3D up() {
return nodes[4];
}
public Node3D down() {
return nodes[5];
}
}
public class NodeController3D {
public NodeController3D(int length, int width, int height) {
HEAD = new Node3D();
pnc(HEAD, length, width, height);
}
private void pnc(Node3D node, int xMax, int yMax, int zMax) {
if(node.nodes == null) {
node.nodes = new Node3D[5];
}
if (node.x < xMax) {
Node3D newNode = node.nodes[2] = new Node3D();
newNode.x = node.x + 1;
newNode.y = node.y;
newNode.z = node.z;
System.out.println(newNode.x + ", " + newNode.y + ", " + newNode.z);
pnc(newNode, xMax, yMax, zMax);
}
if (node.y < yMax) {
Node3D newNode = node.nodes[0] = new Node3D();
newNode.x = node.x;
newNode.y = node.y + 1;
newNode.z = node.z;
pnc(newNode, xMax, yMax, zMax);
}
if (node.z < zMax) {
Node3D newNode = node.nodes[4] = new Node3D();
newNode.x = node.x;
newNode.y = node.y;
newNode.z = node.z + 1;
pnc(newNode, xMax, yMax, zMax);
}
}
// public NodeController3D(int radius) {
//
// }
public final Node3D HEAD;
}
EDIT: Okay I have now updated the code and removed that silly mistake, however it's still not operating exactly as intended. It does seem to be generating the 10x10x10 list, however its running infinitely. Initialized with (10, 10, 10), it should create 10000 objects and stop. I'm just trying to create a list to represent a 3d coordinate plane and each integer coordinate is one node, accessible by direction pointer.
You are running into an infinite recursion.
So what is happening.
You are creating a new Array.
if(node.nodes == null) {
node.nodes = new Node3D[5];
}
You go on by using a Node3D as a newNode variable. This happens because node.x<xMax will be true. -> Node3D newNode = node.nodes[2] = new Node3D();.
You recursivly call pnc now, with this newNode.
So what happens now, node.y<yMax will be true .
Now you reassign the newNode. Node3D newNode = node.nodes[0] = new Node3D();.
and call pnc recursivly again. But you are running into a problem now. since it is a new Node3D your node.x<xMax will be true again and these two steps are happening again and ininite until you are getting your mentioned error.
To fix this error you might want to copy node.x and node.y into your newly created variable.
By changing the assignment you could jump out of the infinite recursion.
if (node.x < xMax) {
if (node.nodes[2] == null) {
node.nodes[2] = new Node3D();
}
Node3D newNode = node.nodes[2];
newNode.x = node.x + 1;
newNode.y = node.y;
newNode.z = node.z;
pnc(newNode, xMax, yMax, zMax);
}
if (node.y < yMax) {
if (node.nodes[0] == null) {
node.nodes[0] = new Node3D();
}
Node3D newNode = node.nodes[0];
newNode.x = node.x;
newNode.y = node.y + 1;
newNode.z = node.z;
pnc(newNode, xMax, yMax, zMax);
}
if (node.z < zMax) {
if (node.nodes[4] == null) {
node.nodes[4] = new Node3D();
}
Node3D newNode = node.nodes[4];
newNode.x = node.x;
newNode.y = node.y;
newNode.z = node.z + 1;
pnc(newNode, xMax, yMax, zMax);
}
But since i don´t know what you are trying to achive with this specific elements at these specifics index in your array this might be a wrong solution for you.
Whenever you create a new Node3D, the variables x, y and z are not initialized, therefore they will evaluate to 0 if accessed.
In the pnc method, there will always be cases where either x < xMax, y < yMax or z < zMax since those are all set to 1.
A good practice is to make variables private and final where possible:
class Node3D {
private final Node3D[] nodes;
private final int x;
private final int y;
private final int z;
public Node3D(int x, int y, int z) {
this.nodes = new Node3D[6];
this.x = x;
this.y = y;
this.z = z;
}
}
This will prevent these kinds of errors in the future. You can create getter methods for the variables. If you really need to reassign the values for x, y or z, you could instead create a new Node3D so that the object can remain immutable.
You were navigating to nodes in the 3D grid in multiple ways. For example, you went to (1,1,0) both from (1,0,0) and (0,1,0), creating duplicates for the same coordinate. This way, you create a number of nodes equal to the total sum of cube paths for each node.
An other approach is to populate a cube of nodes, and give each node a reference to the cube that they are in. Then when you need to go North, you just let the cube return the right node, using the coordinates of the current node. You could use Apache's MultiKeyMap as a grid:
class Node3D {
private static int instances = 0;
public final int x;
public final int y;
public final int z;
public final int number;
public final MultiKeyMap<Integer, Node3D> gridMap;
public Node3D(MultiKeyMap<Integer, Node3D> gridMap, int x, int y, int z) {
this.gridMap = gridMap;
this.x = x;
this.y = y;
this.z = z;
this.number = instances++;
}
//Add/alter these methods according to your orientation
//Returns null if no value is present, you might want to handle this
public Node3D getNorthNode() {
return gridMap.get(this.x + 1, this.y, this.z);
}
//Other getters omitted
#Override
public String toString() {
return "Node3D#" + number + "[" + x + ", " + y + ", " + z + "]";
}
}
Now initialization can be done as follows:
MultiKeyMap<Integer, Node3D> gridMap = new MultiKeyMap<>();
for(int x = 0; x < xMax; x++) {
for(int y = 0; y < yMax; y++) {
for(int z = 0; z < zMax; z++) {
gridMap.put(x, y, z, new Node3D(gridMap, x, y, z));
}
}
}
System.out.println(gridMap.get(4, 4, 4).getNorthNode());

all possible paths for the robot [duplicate]

This question already has answers here:
Algorithm for finding all paths in a NxN grid
(11 answers)
Closed 6 years ago.
Imagine a robot sitting on the upper left hand corner of an NxN grid. The robot can only move in two directions: right and down. Imagine certain squares are “off limits”, such that the robot can not step on them. Design an algorithm to get all possible paths for the robot.
Here is the reference implementation I got, I think the implementation is wrong since it only find one path, other than all possible paths (more details, in line 10, the robot only goes down if no valid path in right. But to find all possible paths, the robot should try both right and down)? Want to confirm my understanding is correct.
ArrayList<Point> current_path = new ArrayList<Point>();
public static boolean getPaths(int x, int y) {
Point p = new Point(x, y);
current_path.add(p);
if (0 == x && 0 == y) return true; // current_path
boolean success = false;
if (x >= 1 && is_free(x - 1, y)) { // Try right
success = getPaths(x - 1, y); // Free! Go right
}
if (!success && y >= 1 && is_free(x, y - 1)) { // Try down
success = getPaths(x, y - 1); // Free! Go down
}
if (!success) {
current_path.remove(p); // Wrong way!
}
return success;
}
thanks in advance,
Lin
Here's what you can do:
public static class Point {
int x, y;
public Point (int x, int y) {
this.x = x;
this.y = y;
}
#Override
public String toString() {
return String.format("[%d, %d]", x, y);
}
}
public static void getPathsRec(int x, int y, Deque<Point> currentPath,
List<List<Point>> paths) {
if (x == 0 && y == 0) {
List<Point> path = new ArrayList<Point>();
for (Point p : currentPath)
path.add(p);
paths.add(path);
//System.out.println(currentPath);
return;
}
if (x > 0 && is_free(x-1, y)) {
currentPath.push(new Point(x-1, y));
getPathsRec(x-1, y, currentPath, paths);
currentPath.pop();
}
if (y > 0 && is_free(x, y-1)) {
currentPath.push(new Point(x, y-1));
getPathsRec(x, y-1, currentPath, paths);
currentPath.pop();
}
}
static int n = 2;
public static List<List<Point>> getPaths() {
List<List<Point>> paths = new ArrayList<List<Point>>();
Deque<Point> d = new ArrayDeque<Point>();
d.push(new Point(n-1, n-1));
getPathsRec(n - 1, n - 1, d, paths);
//System.out.println(paths);
return paths;
}
This is a simple backtracking. The idea is to visit the next state recursively but to make sure that after the call the state goes back to it's previous state(like it was before the call). Here this is done with popping the element from the Deque.
Notice that for simplicity you could introduce new class Path which would be something like:
class Path {
List<Point> points;
}
to make the code more readable. Then getPaths() would return List<Path> which is much nicer.
Also consider redefining getPathsRec to have the signature getPathsRec(Point p, Deque<Point>, List<Path> ), that is having one argument Point instead of having x, y. Having x, y seems redundant considering the fact that you've defined class Point. Again this would make it look better.
Your solution is wrong because once the it reach (0 == x && y==0), the success value will always set to true. Hence, it wouldn't go into later if
Below is the sample answer for your problem. It uses backtracking algorithm:
public class test {
static int n = 3; //substitute your n value here
static ArrayList<Point> current_path = new ArrayList<Point>();
static boolean[][] blockedCell = new boolean[n][n];
public static void FindAllWay(int x, int y)
{
if (x <0 || y < 0) return;
Point p = new Point(x, y);
current_path.add(p);
if (0 == x && 0 == y){
System.out.println(current_path.toString());
current_path.remove(current_path.size()-1);
return;
}
if ((x > 0) && !blockedCell[x-1][y]) //go right
{
blockedCell[x-1][y] = true;
FindAllWay(x-1, y);
blockedCell[x-1][y] = false;
}
if ((y > 0) &&!blockedCell[x][y-1]) // go down
{
blockedCell[x][y-1] = true;
FindAllWay(x, y-1);
blockedCell[x][y-1] = false;
}
current_path.remove(current_path.size()-1);
}
public static void main(String[] args)
{
FindAllWay(n-1,n-1);
}
}

Categories