메모리: 22800 KB, 시간: 160 ms
브루트포스 알고리즘, 깊이 우선 탐색, 그래프 이론, 그래프 탐색
2024년 8월 29일 13:07:47
5×5 크기의 숫자판이 있다. 각각의 칸에는 숫자(digit, 0부터 9까지)가 적혀 있다. 이 숫자판의 임의의 위치에서 시작해서, 인접해 있는 네 방향으로 다섯 번 이동하면서, 각 칸에 적혀있는 숫자를 차례로 붙이면 6자리의 수가 된다. 이동을 할 때에는 한 번 거쳤던 칸을 다시 거쳐도 되며, 0으로 시작하는 000123과 같은 수로 만들 수 있다.
숫자판이 주어졌을 때, 만들 수 있는 서로 다른 여섯 자리의 수들의 개수를 구하는 프로그램을 작성하시오.
다섯 개의 줄에 다섯 개의 정수로 숫자판이 주어진다.
첫째 줄에 만들 수 있는 수들의 개수를 출력한다.
DFS로 전체 경로를 모두 검사하고, Set을 통해 중복을 제거한 후 size()를 출력했다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Main {
//DFS 문제
static int[][] arr = new int[6][6];
static Set<String> sets = new HashSet<String>();
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
for(int i=1; i<=5; i++) {
st = new StringTokenizer(br.readLine());
for(int j=1; j<=5; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
for(int i=1; i<=5; i++) {
for(int j=1; j<=5; j++) {
DFS(i,j,"");
}
}
System.out.println(sets.size());
}
public static void DFS(int x,int y,String num) {
if(num.length()==6) {
sets.add(num);
return;
}
for(int i=0; i<4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >5 || nx<1 || ny>5 || ny<1) {
continue;
}
DFS(nx,ny,num+Integer.toString(arr[nx][ny]));
}
}
}