|
| 1 | +package org.collins; |
| 2 | + |
| 3 | +import org.collins.model.Point; |
| 4 | + |
| 5 | +import java.util.List; |
| 6 | +import java.util.stream.Collectors; |
| 7 | +import java.util.stream.Stream; |
| 8 | + |
| 9 | +public class PathFinder { |
| 10 | + |
| 11 | + public List<Point> findPath(List<String> plane) { |
| 12 | + if (plane.isEmpty()) |
| 13 | + return null; |
| 14 | + |
| 15 | + Point start = new Point(0, 0); |
| 16 | + Point end = new Point(plane.get(0).length() - 1, plane.size() - 1); |
| 17 | + |
| 18 | + return _findPath(plane, start, end, List.of()); |
| 19 | + } |
| 20 | + |
| 21 | + private List<Point> _findPath(List<String> plane, Point start, Point end, List<Point> path) { |
| 22 | + // base case |
| 23 | + if (start.equals(end)) { |
| 24 | + path.add(end); |
| 25 | + return path; |
| 26 | + } |
| 27 | + |
| 28 | + if (start.getY() >= plane.size() || start.getX() >= plane.get(0).length()) { |
| 29 | + return null; |
| 30 | + } |
| 31 | + |
| 32 | + // is this a dead end |
| 33 | + if (plane.get(start.getY()).charAt(start.getX()) == '#') { |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + ///// recurse down and to the left |
| 38 | + |
| 39 | + // add this location to the path |
| 40 | + List<Point> newPath = Utils.append(path, start); |
| 41 | + |
| 42 | + Point right = new Point(start.getX() + 1, start.getY()); |
| 43 | + Point down = new Point(start.getX(), start.getY() + 1); |
| 44 | + |
| 45 | + // can we go down |
| 46 | + if (down.getY() < plane.size()) { |
| 47 | + List<Point> downResult = _findPath(plane, down, end, newPath); |
| 48 | + if (downResult != null) { |
| 49 | + return downResult; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + // can we go right |
| 54 | + if (right.getX() < plane.get(0).length()) { |
| 55 | + List<Point> rightResult = _findPath(plane, right, end, newPath); |
| 56 | + return rightResult; |
| 57 | + } |
| 58 | + return null; |
| 59 | + } |
| 60 | +} |
0 commit comments