Reputation: 1651
input:
3,4,8,7,3
5,S,7,2,3,
8,5,5,8,10
9,3,3,8,7
6,10,3,G,1
the goal is to find the optimal path from the start (S) to the goal (G).
we can move upwards, downwards, to the left and to the right.
the cost is the sum of all elements on the path.
my idea was to use backtracking, however so far i have only managed to find a path, but it is far from optimal.
public List<Point> getNeighbours(Point p, int[][] grid) {
List<Point> neighbours = new LinkedList<>();
if (p.getX() > 0) {
neighbours.add(new Position(p.getX() - 1, p.getY()));
}
if (p.getX() < grid.length - 1) {
neighbours.add(new Position(p.getX() + 1, p.getY()));
}
if (p.getY() > 0) {
neighbours.add(new Point(p.getX(), p.getY() - 1));
}
if (p.getY() < grid[p.getX()].length - 1) {
neighbours.add(new Point(p.getX(), p.getY() + 1));
}
return neighbours;
}
private class IntBox {
int value;
public IntBox(int value) {
this.value = value;
}
}
private boolean findPath(int[][] grid, Point current, Point goal LinkedList<Point> path, Set<Point> visited, IntBox minDist, int dist) {
if (current.getX() == goal.getX() && current.getY() == goal.getY()) {
minDist.value = Math.min(dist, minDist.value);
return true;
}
for (Point neighbour : getNeighbours(current, grid)) {
if (visited.contains(neighbour)) {
continue;
}
visited.add(nachbar);
if (findPath(grid, neighbour, goal, path, visited, minDist, dist+grid[neighbour.getX()][neighbour.getY()])) {
path.addFirst(nachbar);
return true;
}
}
return false;
}
Upvotes: 0
Views: 1074
Reputation: 8421
Take a look at the Dijkstra's algorithm or some other shortest path problem solutions.
The solution could be like this:
S
and then move to a node with the lowest minimal cost value. For an animated example, see Wikipedia.G
as well and you can track the path with the lowest cost using the new field.Upvotes: 1