-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
92 lines (81 loc) · 2.61 KB
/
Copy pathSolution.java
File metadata and controls
92 lines (81 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.*;
import java.io.*;
import java.math.*;
import java.util.stream.Collectors;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Solution {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int w = in.nextInt();
int h = in.nextInt();
int startRow = in.nextInt();
int startCol = in.nextInt();
int n = in.nextInt();
if (in.hasNextLine()) {
in.nextLine();
}
Integer bestMap = null;
MapResult bestResult = null;
for (int i = 0; i < n; i++) {
char[][] map = new char[h][w];
for (int j = 0; j < h; j++) {
String mapRow = in.nextLine();
map[j] = mapRow.toCharArray();
System.err.println(mapRow);
}
MapResult result = runMap(map, startRow, startCol, 0);
if (result.foundTreasure) {
if ((bestMap == null && bestResult == null) || result.pathLength < bestResult.pathLength) {
bestResult = result;
bestMap = i;
}
}
}
// Write an answer using System.out.println()
// To debug: System.err.println("Debug messages...");
System.out.println(bestMap != null ? bestMap : "TRAP");
}
private static MapResult runMap(char[][] map, int row, int col, int pathLength) {
System.err.println("Exploring map ("+ map.length + "x" + map[0].length + ") at row=" + row + ", col=" + col);
if (row >= map.length || col >= map[0].length ) {
return new MapResult(false);
}
char ch = map[row][col];
map[row][col] = '.';
switch (ch) {
case '^':
row--;
break;
case 'v':
row++;
break;
case '<':
col--;
break;
case '>':
col++;
break;
case 'T':
pathLength++;
return new MapResult(true, pathLength);
default:
return new MapResult(false);
}
pathLength++;
return runMap(map, row, col, pathLength);
}
}
class MapResult {
boolean foundTreasure;
int pathLength;
public MapResult(boolean foundTreasure) {
this.foundTreasure = foundTreasure;
}
public MapResult(boolean foundTreasure, int pathLength) {
this.foundTreasure = foundTreasure;
this.pathLength = pathLength;
}
}