Skip to content

Commit 7a1b24c

Browse files
authored
[20250705] BOJ / G3 / 피리 부는 사나이 / 이강현
1 parent 274ddaa commit 7a1b24c

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
public class Main{
6+
static class pos{
7+
int i,j;
8+
pos(int i,int j){
9+
this.i=i;
10+
this.j=j;
11+
}
12+
13+
@Override
14+
public boolean equals(Object obj) {
15+
if(this == obj) return true;
16+
if(obj == null || getClass() != obj.getClass()) return false;
17+
pos other = (pos)obj;
18+
return i==other.i && j==other.j;
19+
}
20+
21+
@Override
22+
public int hashCode() {
23+
return Objects.hash(i, j);
24+
}
25+
}
26+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
27+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
28+
static StringTokenizer st;
29+
static int N,M;
30+
static pos[][] parent;
31+
public static void main(String[] args) throws Exception{
32+
st = new StringTokenizer(br.readLine());
33+
N = Integer.parseInt(st.nextToken());
34+
M = Integer.parseInt(st.nextToken());
35+
36+
parent = new pos[N][M];
37+
for (int i = 0; i < N; i++) {
38+
for (int j = 0; j < M; j++) {
39+
parent[i][j] = new pos(i,j);
40+
}
41+
}
42+
43+
for (int i = 0; i < N; i++) {
44+
String line = br.readLine();
45+
for (int j = 0; j < M; j++) {
46+
char cmd = line.charAt(j);
47+
if(cmd == 'U' && i != 0){
48+
merge(i,j,i-1,j);
49+
}else if(cmd == 'D' && i != N-1){
50+
merge(i,j,i+1,j);
51+
}else if(cmd == 'L' && j != 0){
52+
merge(i,j,i,j-1);
53+
}else if(cmd == 'R' && j != M-1){
54+
merge(i,j,i,j+1);
55+
}
56+
}
57+
}
58+
Set<pos> s = new HashSet<>();
59+
for (int i = 0; i < N; i++) {
60+
for (int j = 0; j < M; j++) {
61+
s.add(find(i,j));
62+
}
63+
}
64+
bw.write(s.size()+"");
65+
bw.close();
66+
}
67+
static pos find(int i,int j){
68+
if(parent[i][j] != null){
69+
if(parent[i][j].i == i && parent[i][j].j == j){
70+
return parent[i][j];
71+
}
72+
else{
73+
return parent[i][j] = find(parent[i][j].i,parent[i][j].j);
74+
}
75+
}
76+
return null;
77+
}
78+
static void merge(int i,int j,int k,int l){
79+
pos a = find(i,j);
80+
pos b = find(k,l);
81+
82+
if(a != null && b != null){
83+
if(a.equals(b)){
84+
return;
85+
}else{
86+
parent[a.i][a.j] = b;
87+
}
88+
}
89+
}
90+
}
91+
```

0 commit comments

Comments
 (0)