Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

이연주 : boj 18352 특정 거리의 도시 찾기 #242

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

Joylish
Copy link
Contributor

@Joylish Joylish commented May 3, 2021

🅰 설계

1. 도시 간 관계

도시 간 관계는 양방향이 아니라 단방향 관계이다

ArrayList<Integer>[] adj = new ArrayList[numOfCity + 1];
for (int i = 1; i <= numOfCity; i++) {
    adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < numOfRoad; i++) {
    st = new StringTokenizer(br.readLine());
    int a = Integer.parseInt(st.nextToken());
    int b = Integer.parseInt(st.nextToken());
    adj[a].add(b);
}

2. 전체 도시 탐방

주어진 최소 거리만큼 떨어진 도시가 있는지 확인

Queue<Integer> q = new ArrayDeque<>();
int[] isVisited = new int[numOfCity + 1];
Arrays.fill(isVisited, -1);
q.add(startCity);
isVisited[startCity] = 0;
boolean isThere = false;
while (!q.isEmpty()) {
    int now = q.poll();
    for (int next : adj[now]) {
        if (isVisited[next] != -1) continue;
        q.add(next);
        isVisited[next] = isVisited[now] + 1;
        if (isVisited[next] == minDist) isThere = true;
    }
}

3. 결과 도출

  • isThere : 주어진 최소거리만큼 떨어진 도시가 있다면 true가 되는 변수

    isThere이 true가 아니면 주어진 최소거리만큼 떨어진 도시가 없다는 것으로 -1을 출력한다. 그 반대이면 주어진 최소거리만큼 떨어진 도시를 StringBuilder에 추가한다.

if (!isThere) {
    System.out.println(-1);
    return;
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= numOfCity; i++) {
    if (minDist != isVisited[i]) continue;
    sb.append(i).append("\n");
}
System.out.println(sb);

✅ 후기

  • 싸피에서 자주 푸는 그래프 문제 유형이라서 bfs로 접근하여 빠르게 푼 것 같습니다

@Joylish Joylish added BFS/DFS 그래프 탐색 BOJ Baekjoon labels May 3, 2021
@Joylish Joylish self-assigned this May 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BFS/DFS 그래프 탐색 BOJ Baekjoon
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant