-
Notifications
You must be signed in to change notification settings - Fork 138
/
Solution.java
108 lines (90 loc) · 3.01 KB
/
Solution.java
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import java.io.*;
import java.util.*;
class Pair {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class State {
Pair p;
int counter;
State(Pair position) {
this.p = position;
this.counter = 0;
}
State(Pair position, int counter) {
this.p = position;
this.counter = counter;
}
}
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for (int i = 0; i < q; i++) {
int N = sc.nextInt();
int M = sc.nextInt();
Pair start = new Pair(0, 0), end = new Pair(0, 0);
int[][] board = new int[N][M];
for (int j = 0; j < N; j++) {
String line = sc.next();
for (int k = 0; k < M; k++) {
if (line.charAt(k) == 'X') {
board[j][k] = -1;
} else if (line.charAt(k) == 'M') {
board[j][k] = 0;
start = new Pair(j, k);
} else if (line.charAt(k) == '*') {
board[j][k] = 0;
end = new Pair(j, k);
}
}
}
int K = sc.nextInt();
// Solve problem here
LinkedList<State> queue = new LinkedList<State>();
queue.addFirst(new State(start));
while (queue.size() > 0) {
State current = queue.pollLast();
Pair p = current.p;
ArrayList<Pair> nextMove = new ArrayList<Pair>();
if (p.x == end.x && p.y == end.y) {
board[p.x][p.y] = current.counter;
break;
} else {
board[p.x][p.y] = -1;
}
// Right
if (p.y + 1 < M && board[p.x][p.y + 1] == 0) {
nextMove.add(new Pair(p.x, p.y + 1));
}
// Left
if (p.y - 1 >= 0 && board[p.x][p.y - 1] == 0) {
nextMove.add(new Pair(p.x, p.y - 1));
}
// Up
if (p.x - 1 >= 0 && board[p.x - 1][p.y] == 0) {
nextMove.add(new Pair(p.x - 1, p.y));
}
// Down
if (p.x + 1 < N && board[p.x + 1][p.y] == 0) {
nextMove.add(new Pair(p.x + 1, p.y));
}
if (nextMove.size() > 1) {
current.counter++;
}
for (int g = 0; g < nextMove.size(); g++) {
current.p = nextMove.get(g);
queue.addFirst(new State(new Pair(current.p.x, current.p.y), current.counter));
}
}
if (board[end.x][end.y] == K) {
System.out.println("Impressed");
} else {
System.out.println("Oops!");
}
}
}
}