https://www.acmicpc.net/problem/1388
- '-' ์ด๋ฐ ๋ฌธ์๊ฐ ๋์ค๋ฉด -> ์ด ๋ฐฉํฅ์ผ๋ก ํ์, '|' ์ด๋ฐ ๋ฌธ์๊ฐ ๋์ค๋ฉด ↓ ์ด ๋ฐฉํฅ์ผ๋ก ํ์ํ๋ค๊ณ ์๊ฐํ๋ฉด ๋๋ค.
- ์ฌ๊ธฐ์ ์ด๋ค ๊ฒฝ์ฐ์ ์ธ์ ๋ฆฌ์คํธ๋ฅผ ์ฌ์ฉํ๊ณ ์ด๋ค ๊ฒฝ์ฐ์ 2์ฐจ์ ๋ฐฐ์ด์ ์ฌ์ฉํ๋์ง๊ฐ ๊ถ๊ธํด์ก๋ค.
* ์ธ์ ๋ฆฌ์คํธ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ
- ์ ์ ์ด ๋ง๊ณ , ๊ฐ ์ ์ ์ ์ฐ๊ฒฐ๋ ๊ฐ์ ์ ์๊ฐ ์ ์ ๋
- ์ ์ ์ค์ฌ์ ํ์
- ์ ๋ ฅ์ด ์ ์ -๊ฐ์ ๋ชฉ๋ก์ผ๋ก ์ฃผ์ด์ง ๋
* 2์ฐจ์ ๋ฐฐ์ด(๊ทธ๋ฆฌ๋, ์ธ์ ํ๋ ฌ)์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ
- ์ ์ ๊ฐ์์ ๋นํด ๊ฐ์ ๊ฐ์๊ฐ ๋ง์ ๋ ( ์ : N x N ํ๋ ฌ์์ ๋ชจ๋ ์ ์ ์ด ์ฐ๊ฒฐ๋ ์์ ๊ทธ๋ํ )
- ๊ทธ๋ํ๊ฐ 2D ๊ฒฉ์ ํํ์ผ ๋ ( ์ : ๋ฏธ๋ก์ฐพ๊ธฐ, ์ฌ์ ๊ฐ์, ๊ฒฝ๋ก ํ์ ๋ฑ )
- ์ ์ ๊ฐ ์ฐ๊ฒฐ ์ฌ๋ถ ์ฒดํฌํ ๋ ( ์ : ๊ฒฝ๋ก ์กด์ฌ ํ์ธ )
- ๊ฒฐ๋ก
- ๊ทธ๋ํ์ ํฌ๊ธฐ์ ์ฐ๊ฒฐ ์ ๋ณด์ ๋ฐ๋ ํ์
- ์ ์ ์์ ๊ฐ์ ์๊ฐ ์ ๊ณ ํ์์ด ๊ฒฉ์ ํํ๋ผ๋ฉด? 2์ฐจ์ ๋ฐฐ์ด
- ์ ์ ์๊ฐ ๋ง๊ณ ๊ฐ์ ์ ๋ณด๊ฐ ํฌ์ํ๋ค๋ฉด? ์ธ์ ๋ฆฌ์คํธ
- DFS (๊น์ด์ฐ์ ํ์) ๋ฅผ ์ ์ฉํด์ ํ์ดํ๋ค.
- ์ค๋ฅธ์ชฝ ๋ฐฉํฅ์ผ๋ก ํ์ ๋ฐ๋ผ์ ํ์์ ์ ๊ฐํ๋ค '|' ๋ฌธ์๋ฅผ ๋ง๋๋ฉด ์๋ ๋ฐฉํฅ์ผ๋ก ์ด์ ๋ฐ๋ผ ํ์ํ๋ค.
- 2์ฐจ์ ๋ฐฐ์ด๋ก ๋ฐฉ๋ฌธ์ฌ๋ถ์ ๋ฌธ์์ด์ด ๋ด๊ธด ๊ทธ๋ฆฌ๋๋ฅผ ๋ง๋ ๋ค.
- DFS ํ์ ๋ฉ์๋์์ ํ๊ณผ ์ด์ ๋์ ์ฒดํฌํ๊ธฐ ์ํด N,M ๋ณ์๋ฅผ ์ฌ์ฉํด์ผ ํ๊ธฐ ๋๋ฌธ์ static ์ ์ญ ๋ณ์๋ก ์ ์ธํ๋ค.
ํ์ด
import java.io.*;
import java.util.*;
public class Main{
static boolean[][] visited;
static char[][] graph;
static int cnt;
static int N,M;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
N = Integer.parseInt(str[0]);
M = Integer.parseInt(str[1]);
visited = new boolean[N+1][M+1];
graph = new char[N+1][M+1];
for(int i=1; i<N+1; i++){
char[] c = br.readLine().toCharArray();
for(int j=1; j<M+1; j++){
graph[i][j] = c[j-1];
}
}
//๋ฐฉ๋ฌธํ์
for(int i=1; i<N+1; i++){
for(int j=1; j<M+1; j++){
if(!visited[i][j]){
dfs(i, j);
}
}
}
//์ถ๋ ฅ
System.out.println(cnt);
}
//DFS ํ์
private static void dfs(int i, int j){
visited[i][j] = true;
if(graph[i][j]=='-'){ //->
if(j==M){ //ํ์ ๋์ด๋ฉด
cnt++;
return;
}
int nextY = j+1;
if(!visited[i][nextY] && graph[i][nextY] == '-'){ //๋ฐฉ๋ฌธํ์ ์๊ณ '-'์ด๋ฉด
dfs(i, nextY); //์ฌ๊ทํธ์ถ
}else{
cnt++;
return;
}
}
if(graph[i][j] == '|'){ //↓
if(i==N){ //์ด์ ๋์ด๋ฉด
cnt++;
return;
}
int nextI = i+1;
if(!visited[nextI][j] && graph[nextI][j] == '|'){ //๋ฐฉ๋ฌธํ์ ์์ผ๋ฉด์ '|'์ด๋ฉด
dfs(nextI, j); //์ฌ๊ทํธ์ถ
}else{
cnt++;
return;
}
}
}
}
'Algorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Silver I/JAVA] 2583 ์์ญ ๊ตฌํ๊ธฐ (0) | 2024.12.12 |
---|---|
[Silver II/JAVA] 2210 ์ซ์ํ ์ ํ (0) | 2024.12.12 |
[Silver II/JAVA] 1260 DFS์ BFS (1) | 2024.12.10 |
[Silver II/JAVA] 24479, 24480 ์๊ณ ๋ฆฌ์ฆ ์์ - ๊น์ด ์ฐ์ ํ์ 1, 2 (0) | 2024.12.01 |
[Silver III/JAVA] 10451 ์์ด ์ฌ์ดํด (0) | 2024.11.23 |