티스토리 뷰
import java.io.*;
import java.util.*;
public class Main {
static int N, M, person1, person2, x, y;
static LinkedList<Integer>[] nodeList;
static boolean[] visited;
static boolean check;
static class Node {
int index;
int distance;
public Node(int index, int distance) {
this.index = index;
this.distance = distance;
}
}
public static void bfs(int start, int end) {
Queue<Node> q = new LinkedList<>();
q.offer(new Node(start, 0));
while (!q.isEmpty()) {
Node now = q.poll();
if (visited[now.index]) return;
visited[now.index] = true;
if (now.index == end) {
System.out.println(now.distance);
check = true;
return;
}
for (int next : nodeList[now.index]) {
if (!visited[next]) {
q.offer(new Node(next, now.distance+1));
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
person1 = Integer.parseInt(st.nextToken());
person2 = Integer.parseInt(st.nextToken());
nodeList = new LinkedList[N+1];
visited = new boolean[N+1];
for (int i = 0; i <= N; i++) {
nodeList[i] = new LinkedList<Integer>();
}
M = Integer.parseInt(br.readLine());
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
nodeList[x].add(y);
nodeList[y].add(x);
}
bfs(person1, person2);
if (!check) {
System.out.println(-1);
}
}
}
- 될거 같은데 계속 틀림 ....
- 다른 풀이 보고 다시 품
- 혼자서 생각이 안난다 ....
0. bfs 생각
1. 연결관계 입력
2. bfs 수행 - Queue
2-1) 촌수를 계산할 변수가 필요해서 Node에 넣어서 사용
2-2) 큐에서 꺼낸 노드의 인덱스 값이 end와 같다면 distance 출력
2-3) 방문하지 않았을경우에만 꺼낸 노드의 인덱스와 연결된 노드들을 다시 큐에 추가 거리 +1
반응형
'PS > boj' 카테고리의 다른 글
boj)9093 - 단어 뒤집기 (0) | 2020.09.13 |
---|---|
boj)10828 - 스택구현 (0) | 2020.09.13 |
boj)7576 - 토마토 (0) | 2020.09.05 |
boj)2178 - 미로 탐색 (0) | 2020.09.03 |
boj)1012 - 유기농 배추 (0) | 2020.09.03 |
링크
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- GCP
- 집 구하기
- js array
- HTTP 완벽 가이드
- 백준
- 프로그래머스
- 이펙티브자바 아이템59
- 킹수빈닷컴
- 드림코딩
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- java
- 백기선 스터디
- 모던자바스크립트
- js api
- JS 딥다이브
- 김영한 http
- 이펙티브자바
- 프로그래머스 SQL
- http
- REST API
- 이펙티브자바 아이템60
- 김영한 JPA
- HTTP 완벽가이드
- js promise
- Spring Security
- BOJ
- dreamcoding
- 패스트캠퍼스 컴퓨터공학 완주반
- 이펙티브자바 스터디
- JPA 연관관계 매핑
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
31 |
글 보관함