2210번: 숫자판 점프
111111, 111112, 111121, 111211, 111212, 112111, 112121, 121111, 121112, 121211, 121212, 211111, 211121, 212111, 212121 이 가능한 경우들이다.
www.acmicpc.net
👇 내가 작성한 코드
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 {
static Set<String> set;
static int[] dr = {1, 0, -1, 0};
static int[] dc = {0, 1, 0, -1};
static int[][] map;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
map = new int[5][5];
for(int i = 0; i < 5; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0; j < 5; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
set = new HashSet<>();
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
DFS(i, j, "", 0);
}
}
System.out.println(set.size());
}
public static void DFS(int x, int y, String result, int count) {
if(count == 6) {
set.add(result);
return;
}
for(int d = 0; d < 4; d++) {
int nr = dr[d] + x;
int nc = dc[d] + y;
if(nr >= 0 && nc >= 0 && nr < 5 && nc < 5) {
DFS(nr, nc, result + map[nr][nc], count + 1);
}
}
}
}
느낀 점 및 정리 ✍️
1. Set을 이용하여 중복 제거
2. 동일한 곳을 재방문할 수 있기 때문에 visited 방문 배열을 별도로 사용하지 않았다.
3. 5글자가 만들어지면 return 되게끔 String과 count를 파라미터로 넘겨주었다.
'Algorithm & SQL > BOJ' 카테고리의 다른 글
[백준 15565번 / Java] BOJ 15565 : 귀여운 라이언(투 포인터) (0) | 2024.03.26 |
---|---|
[백준 1972번 / Java] BOJ 1972 : 놀라운 문자열 (0) | 2024.03.26 |
[백준 16173번 / Java] BOJ 16173 : 점프왕 쩰리 (Small) (0) | 2024.03.24 |
[백준 2309번 / Java] BOJ 2309 : 일곱 난쟁이 (0) | 2024.03.16 |
[백준 3649번 / Java] BOJ 3649 : 로봇 프로젝트(투 포인터) (2) | 2024.03.12 |