https://www.acmicpc.net/problem/2210
์กฐ๊ฑด
- ์ซ์ํ์ ํฌ๊ธฐ๋ 5*5
- ์ธ์ ํ ๋ค ๋ฐฉํฅ์ผ๋ก ๋ค์ฏ๋ฒ ์ด๋ (์, ์๋, ์ค๋ฅธ์ชฝ, ์ผ์ชฝ)
- ํ ๋ฒ ๊ฑฐ์ณค๋ ์นธ์ ๋ค์ ๊ฑฐ์ณ๋ ๋จ = ๋ฐฉ๋ฌธ ์ฒดํฌ ํ์์์
- ์๋ก ๋ค๋ฅธ ์ฌ์ฏ ์๋ฆฌ ์๋ค์ ๊ฐ์ ๊ตฌํ๊ธฐ
ํ์ํ ๊ฒ
- ์ซ์ํ(grid) 2์ฐจ์ ๋ฐฐ์ด
- ๋ฐฉํฅ ์ด๋์ ์ํ ๋ฐฐ์ด dx, dy
- ์ค๋ณต์ ์ ๊ฑฐํ ์ ์๋ Set
ํ์ด
- grid 2์ฐจ์ ๋ฐฐ์ด์ ๊ฐ ์ ๋ ฅ๋ฐ๊ธฐ
- ๊ฐ๊ฐ์ ์ ์ (์ซ์ํ์ ์ซ์)์์ DFS ํ์ํ๊ธฐ
- ์ธ์ ํ ๋ค ๋ฐฉํฅ์ผ๋ก ์ด๋
int[] dx = {1, -1, 0, 0};
int[] dy = {0, 0, 1, -1};
/*
์๋ : dx=1 dy=0 -> ํ ๋ฒํธ 1์ฆ๊ฐ x+1
์ : dx=-1 dy=0 -> ํ ๋ฒํธ 1๊ฐ์ x-1
์ค๋ฅธ์ชฝ : dx=0 dy=1 -> ์ด ๋ฒํธ 1์ฆ๊ฐ y+1
์ผ์ชฝ : dx=0 dy=-1 -> ์ด ๋ฒํธ 1๊ฐ์ y-1
*/
- grid ๋ด์ ์กด์ฌํ๋์ง ์ฒดํฌํ๋ฉด์ DFS ํ์, ๋ฌธ์์ด์ ๊ธธ์ด๊ฐ 6์ด ๋๋ฉด ํ์ ์ข ๋ฃํ๊ณ set์ ๊ฒฐ๊ณผ ์ ์ฅ
- Set ์๋ฃ๊ตฌ์กฐ : ์ค๋ณต๋ ๊ฐ ํ์ฉํ์ง ์์, ์์ ์์
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("A");
System.out.println(set); //์ถ๋ ฅ : [A,B] (์์x)
- set์ ์ฌ์ด์ฆ๋ฅผ ์ถ๋ ฅํ๋ฉด ๊ฒฐ๊ณผ๊ฐ ๋๋ค.
์ ์ฒด ์ฝ๋
import java.io.*;
import java.util.*;
public class Main{
static int[][] grid = new int[5][5];
static int[] dx = {1, -1, 0, 0};
static int[] dy = {0, 0, 1, -1};
static Set<String> set = new HashSet<>();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//grid ์ด๊ธฐํ
for(int i=0; i<5; i++){
String[] str = br.readLine().split(" ");
for(int j=0; j<5; j++){
grid[i][j] = Integer.parseInt(str[j]);
}
}
//DFS ํ์ ๋ชจ๋ ์ ์ ์์
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
dfs(i, j, "", 0); //์ ์ ์์น i,j , ๋ฌธ์์ด, ์ด๋ํ์
}
}
//์ถ๋ ฅ
System.out.println(set.size());
}
private static void dfs(int x, int y, String path, int depth){
if(depth == 6){ //6์๋ฆฌ
set.add(path);
return;
}
//ํ์ฌ ์์น์ ์ซ์๋ฅผ ๋ฌธ์์ด์ ์ถ๊ฐ
path += grid[x][y];
//๋ค ๋ฐฉํฅ์ผ๋ก ์ด๋ (์, ์๋, ์ค๋ฅธ, ์ผ)
for(int i=0; i<4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
//grid๋ด์ ์์นํ๋์ง ์ฒดํฌ -> ๊ณ์ dfsํ์
if(nx >= 0 && nx < 5 && ny >= 0 && ny < 5){
dfs(nx, ny, path, depth+1);
}
}
}
}
'Algorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Silver I/JAVA] 2667 ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (1) | 2024.12.13 |
---|---|
[Silver I/JAVA] 2583 ์์ญ ๊ตฌํ๊ธฐ (0) | 2024.12.12 |
[Silver IV/JAVA] 1388 ๋ฐ๋ฅ์ฅ์ (2) | 2024.12.10 |
[Silver II/JAVA] 1260 DFS์ BFS (1) | 2024.12.10 |
[Silver II/JAVA] 24479, 24480 ์๊ณ ๋ฆฌ์ฆ ์์ - ๊น์ด ์ฐ์ ํ์ 1, 2 (0) | 2024.12.01 |