Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 입실 퇴실
- 재귀
- 그래프
- openssl
- Java
- 부분 수열의 합
- 프로그래머스
- 백준
- 백트래킹
- 백트렉킹
- DP
- 백트랙킹
- 너비우선탐색
- 10597
- 코딩테스트
- 줄어드는 숫자
- 완전 탐색
- 1174
- 39080
- BFS
- 문서자동화
- 위클리 챌린지
- ElementTree
- dfs
- BOJ
- 몯느 순열
- 위클리 6주차
- 복서 정렬하기
- 좋은 수열
- 순열장난
Archives
개발자-H 입니다.
BOJ - 숨바꼭질 (1697) 본문
https://www.acmicpc.net/submit/1697/31937024
로그인
www.acmicpc.net
- 그래프 탐색 문제이나 BFS와 DFS가 섞인 문제이다.
- BFS로 최단 경로를 찾고 DFS로 최단 경로까지 이동을 찾는 문제이다.
import java.util.*;
public class Main {
public static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws Exception {
int N = scanner.nextInt();
int K = scanner.nextInt();
boolean[] visited = new boolean[100000 + 1];
ArrayList<Integer>[] adj = new ArrayList[100000 + 1];
for (int i = 0; i < adj.length; i++) {
adj[i] = new ArrayList<>();
}
ArrayList<State> visitedNodes = new ArrayList<>();
Queue<State> queue = new LinkedList<>();
queue.add(new State(N, 1));
int goldDepth = 1;
while (!queue.isEmpty()) {
State node = queue.poll();
if (node.currentNode < 0 || node.currentNode > 100000) continue;
if (visited[node.currentNode] == true) continue;
visited[node.currentNode] = true;
visitedNodes.add(node);
if (node.currentNode == K) {
goldDepth = node.depth;
break;
}
queue.add(new State(node.currentNode - 1, node.depth + 1));
adj[node.currentNode].add(node.currentNode - 1);
queue.add(new State(node.currentNode + 1, node.depth + 1));
adj[node.currentNode].add(node.currentNode + 1);
queue.add(new State(node.currentNode * 2, node.depth + 1));
adj[node.currentNode].add(node.currentNode * 2);
}
System.out.println(goldDepth - 1);
}
private static void dfs(ArrayList<Integer> path, Integer currentNode, boolean[] visited, ArrayList<Integer>[] adj, int depth, int golaDepth, int goal) {
if (currentNode >= adj.length) return;
if (visited[currentNode] == true) return;
if (depth > golaDepth) return;
visited[currentNode] = true;
path.add(currentNode);
if (currentNode == goal) {
for (int i = 0; i < path.size(); i++) {
System.out.print(path.get(i) + " ");
}
System.exit(0);
return;
}
for (int i = 0; i < adj[currentNode].size(); i++) {
Integer next = adj[currentNode].get(i);
dfs(path, next, visited, adj, depth + 1, golaDepth, goal);
}
visited[currentNode] = false;
path.remove(currentNode);
}
}
class State {
public int currentNode;
public int depth;
public State(int currentNode, int depth) {
this.currentNode = currentNode;
this.depth = depth;
}
}
'Algorithm > 문제 풀이' 카테고리의 다른 글
BOJ - N과 M (2) (0) | 2021.08.11 |
---|---|
BOJ - N과 M (1) (0) | 2021.08.11 |
BOJ - 미로 탐색 (2178) (0) | 2021.08.09 |
BOJ - 바이러스 (0) | 2021.08.08 |
프로그래머스 - 게임 맵 최단 거리 (0) | 2021.08.08 |
Comments