Skip to content

Instantly share code, notes, and snippets.

@SimDing
Created October 8, 2018 21:30
Show Gist options
  • Save SimDing/9e00e1f3617e0b66ccd9d7059731fd74 to your computer and use it in GitHub Desktop.
Save SimDing/9e00e1f3617e0b66ccd9d7059731fd74 to your computer and use it in GitHub Desktop.
import java.awt.Point;
import java.util.Scanner;
class Main {
public static String CorrectPath(String str) {
return findWay(new Point(0, 0), str);
}
public static String findWay(Point from, String using) {
// check if we are out of the grid
if (from.x < 0 || from.x >= 5) return null;
if (from.y < 0 || from.y >= 5) return null;
// check if we reached the target (4, 4)
if (using.length() == 0) {
if (from.x == 4 && from.y == 4) return "";
else return null;
}
// check in which directions we are allowed to continue
String fst = using.substring(0, 1);
Movement[] movementsToExplore;
if ("?".equals(fst)) {
movementsToExplore = Movement.values();
} else {
movementsToExplore = new Movement[1];
movementsToExplore[0] = Movement.valueOf(fst);
if (movementsToExplore[0] == null) {
throw new RuntimeException("Invalid question");
}
}
// for each direction continue recursively
for (Movement m : movementsToExplore) {
Point nextTile = new Point(from.x + m.x, from.y + m.y);
String way = findWay(nextTile, using.substring(1));
if (way != null) {
return m.toString() + way;
}
}
// there was no way
return null;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(CorrectPath(s.nextLine()));
}
private static enum Movement {
l(-1, 0), r(1, 0), u(0, -1), d(0, 1);
final int x;
final int y;
Movement(int x, int y) {
this.x = x;
this.y = y;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment