-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSAC22C2P4.java
More file actions
78 lines (65 loc) · 1.96 KB
/
SAC22C2P4.java
File metadata and controls
78 lines (65 loc) · 1.96 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
package contest;
import java.io.*;
import java.util.*;
public class SAC22C2P4 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static StringTokenizer st;
static int [][] dir = {{0,1}, {0,-1}, {1,0}, {-1,0}};
public static void main(String[] args) throws IOException {
int n = readInt(), m = readInt();
char [][]grid = new char [n][m];
for (int i = 0; i< n;i++) {
grid[i] = readLine().toCharArray();
}
int[][] dis = new int [n][m];
ArrayDeque<Integer> rows = new ArrayDeque();
ArrayDeque<Integer> cols = new ArrayDeque();
for (int k = 0; k< n;k++) Arrays.fill(dis[k], Integer.MAX_VALUE);
rows.add(0);
cols.add(0);
dis[0][0] = 0;
if (grid[0][0] == 'C')dis[0][0] = 1;
while (!rows.isEmpty()) {
int r = rows.poll();
int c = cols.poll();
for(int [] di : dir) {
int nr = r+di[0];
int nc = c+di[1];
if(Math.min(nr, nc) < 0 || nr >= n || nc >= m)continue;
int w = ((grid[nr][nc] == 'C')?1:0);
if(dis[r][c] +w < dis[nr][nc]) {
dis[nr][nc] = dis[r][c] +w;
if(w == 0) {
rows.addFirst(nr);
cols.addFirst(nc);
}else {
rows.addLast(nr);
cols.addLast(nc);
}
}
}
}
System.out.println(dis[n-1][m-1]);
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readLine() throws IOException {
return br.readLine().trim();
}
}