in.add()
[16928] 뱀과 사다리 게임 본문
문제 링크 : https://www.acmicpc.net/problem/16928
16928번: 뱀과 사다리 게임
첫째 줄에 게임판에 있는 사다리의 수 N(1 ≤ N ≤ 15)과 뱀의 수 M(1 ≤ M ≤ 15)이 주어진다. 둘째 줄부터 N개의 줄에는 사다리의 정보를 의미하는 x, y (x < y)가 주어진다. x번 칸에 도착하면, y번 칸으
www.acmicpc.net
문제 해결 방법
BFS로 구현했다.
package com.BOJ;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class boj16928 {
static HashMap<Integer, Integer> map;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
map = new HashMap<>();
for (int i = 0; i < N + M; i++) {
map.put(sc.nextInt(), sc.nextInt());
}
System.out.println(bfs());
}
private static int bfs() {
int cnt = 1;
Queue<Integer> q = new LinkedList<>();
boolean[] visit = new boolean[101];
visit[1] = true;
q.add(1);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
int cur = q.poll();
for (int j = 1; j <= 6; j++) {
int next = cur + j;
if(next == 100) return cnt;
if(next > 100) break;
if(visit[next]) continue;
if (map.containsKey(next)) {
next = map.get(next);
if(visit[next]) continue;
}
q.add(next);
visit[next] = true;
}
}
cnt++;
}
return cnt;
}
}
'Algorithm > BOJ' 카테고리의 다른 글
[1194] 달이 차오른다, 가자. (0) | 2021.09.29 |
---|---|
[1697] 숨바꼭질 (0) | 2021.09.28 |
[2667] 단지 번호 붙이기 (0) | 2021.09.22 |
[17472] 다리 만들기 2 (0) | 2021.09.18 |
[14003] 가장 긴 증가하는 부분 수열 5 (0) | 2021.09.16 |
Comments