|
| 1 | +``` |
| 2 | +import java.io.*; |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.Set; |
| 5 | +import java.util.StringTokenizer; |
| 6 | +
|
| 7 | +public class Main { |
| 8 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 9 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 10 | + private static Set<Integer> set; |
| 11 | + private static char[][] map; |
| 12 | + private static int[] uf, size; |
| 13 | + private static int N, M; |
| 14 | +
|
| 15 | + public static void main(String[] args) throws IOException { |
| 16 | + init(); |
| 17 | +
|
| 18 | + for (int i = 0; i < N; i++) { |
| 19 | + for (int j = 0; j < M; j++) { |
| 20 | + int x = i*M + j; |
| 21 | + int y = 0; |
| 22 | + int nx = i; |
| 23 | + int ny = j; |
| 24 | + if (map[i][j] == 'U') nx--; |
| 25 | + else if (map[i][j] == 'D') nx++; |
| 26 | + else if (map[i][j] == 'L') ny--; |
| 27 | + else ny++; |
| 28 | +
|
| 29 | + y = nx*M + ny; |
| 30 | + int root1 = find(x); |
| 31 | + int root2 = find(y); |
| 32 | +
|
| 33 | + if (root1 == root2) continue; |
| 34 | + union(root1, root2); |
| 35 | + } |
| 36 | + } |
| 37 | +
|
| 38 | + for (int i = 0; i < N*M; i++) { |
| 39 | + set.add(find(i)); |
| 40 | + } |
| 41 | +
|
| 42 | + bw.write(set.size() + "\n"); |
| 43 | + bw.flush(); |
| 44 | + bw.close(); |
| 45 | + br.close(); |
| 46 | + } |
| 47 | +
|
| 48 | + private static void init() throws IOException { |
| 49 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 50 | + N = Integer.parseInt(st.nextToken()); |
| 51 | + M = Integer.parseInt(st.nextToken()); |
| 52 | +
|
| 53 | + map = new char[N][M]; |
| 54 | +
|
| 55 | + for (int i = 0; i < N; i++) { |
| 56 | + String input = br.readLine(); |
| 57 | + for (int j = 0; j < M; j++) { |
| 58 | + map[i][j] = input.charAt(j); |
| 59 | + } |
| 60 | + } |
| 61 | +
|
| 62 | + uf = new int[N*M]; |
| 63 | + size = new int[N*M]; |
| 64 | +
|
| 65 | + for (int i = 0; i < N*M; i++) { |
| 66 | + uf[i] = i; |
| 67 | + size[i] = 1; |
| 68 | + } |
| 69 | +
|
| 70 | + set = new HashSet<>(); |
| 71 | + } |
| 72 | +
|
| 73 | + private static void union(int x, int y) { |
| 74 | + if (size[x] < size[y]) { |
| 75 | + uf[x] = y; |
| 76 | + size[y] += size[x]; |
| 77 | + } else { |
| 78 | + uf[y] = x; |
| 79 | + size[x] += size[y]; |
| 80 | + } |
| 81 | + } |
| 82 | +
|
| 83 | + private static int find(int x) { |
| 84 | + if (uf[x] == x) return x; |
| 85 | +
|
| 86 | + return uf[x] = find(uf[x]); |
| 87 | + } |
| 88 | +} |
| 89 | +``` |
0 commit comments