-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTask10.java
89 lines (73 loc) · 1.88 KB
/
Task10.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
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Task10 {
static int N;
static int M;
static boolean[][] been;
public static class State {
int y;
int x;
String path;
public State(int y, int x, String path) {
super();
this.y = y;
this.x = x;
this.path = path;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
N = in.nextInt();
M = in.nextInt();
been = new boolean[N][M];
State initial = null;
char[][] map = new char[N][M];
for (int i = 0; i < N; i++) {
String row = in.next();
for (int j = 0; j < M; j++) {
map[i][j] = row.charAt(j);
if (map[i][j] == '*') {
initial = new State(i, j, "");
}
}
}
Queue<State> q = new LinkedList<State>();
q.add(initial);
boolean escaped = false;
while(!q.isEmpty()) {
State s = q.remove();
if (been[s.y][s.x]) {
continue;
}
been[s.y][s.x] = true;
if (finished(s)) {
System.out.println(s.path);
escaped = true;
break;
}
if (map[s.y+1][s.x] == '-') {
q.add(new State(s.y + 1, s.x, s.path + "S"));
}
if (map[s.y][s.x+1] == '-') {
q.add(new State(s.y, s.x + 1, s.path + "E"));
}
if (map[s.y-1][s.x] == '-') {
q.add(new State(s.y - 1, s.x, s.path + "N"));
}
if (map[s.y][s.x-1] == '-') {
q.add(new State(s.y, s.x - 1, s.path + "W"));
}
}
if (!escaped) {
System.out.println("Goodluck");
}
}
public static boolean finished(State s) {
if (s.y == 0 || s.y == N-1)
return true;
if (s.x == 0 || s.x == M-1)
return true;
return false;
}
}