[BaekJoon] 1976 여행 가자 (Java)

오태호·2022년 10월 19일
0

백준 알고리즘

목록 보기
78/395

1.  문제 링크

https://www.acmicpc.net/problem/1976

2.  문제

요약

  • 동혁이는 친구들과 함께 여행을 가려고 하는데, 한국에는 도시가 N개 있고 임의의 두 도시 사이에 길이 있을 수도, 없을 수도 있습니다.
  • 동혁이의 여행 일정이 주어졌을 때, 이 여행 경로가 가능한 것인지 알아보려고 합니다.
  • 중간에 다른 도시를 경유해서 여행을 할 수도 있고 같은 도시를 여러 번 방문할 수도 있습니다.
  • 도시들의 개수와 도시들 간의 연결 여부가 주어져 있고, 동혁이의 여행 계획에 속한 도시들이 순서대로 주어졌을 때 가능한지 여부를 판별하는 문제입니다.
  • 입력: 첫 번째 줄에 200보다 작거나 같은 도시의 수 N이 주어지고 두 번째 줄에 1000보다 작거나 같은 여행 계획에 속한 도시들의 수 M이 주어집니다. 세 번째 줄부터 N개의 줄에 N개의 정수가 주어지는데, i번째 줄의 j번째 수는 i번 도시와 j번 도시의 연결 정보를 의미합니다. 1이면 연결된 것이고 0이면 연결되지 않은 것입니다. A와 B가 연결되었으면 B와 A도 연결되어 있습니다. 마지막 줄에는 여행 계획이 주어집니다.
    • 도시의 번호는 1부터 N까지 차례대로 매겨져 있습니다.
  • 출력: 첫 번째 줄에 가능하면 YES, 불가능하면 NO를 출력합니다.

3.  소스코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
	static int N, M;
	static HashMap<Integer, ArrayList<Integer>> map;
	static boolean[][] canVisit;
	static int[] schedule;
	static void input() {
		Reader scanner = new Reader();
		N = scanner.nextInt();
		M = scanner.nextInt();
		map = new HashMap<>();
		canVisit = new boolean[N + 1][N + 1];
		for(int city = 1; city <= N; city++) map.put(city, new ArrayList<Integer>());
		for(int city = 1; city <= N; city++) {
			for(int connect = 1; connect <= N; connect++) {
				int connectivity = scanner.nextInt();
				if(connectivity == 1) {
					map.get(city).add(connect);
					map.get(connect).add(city);
				}
			}
		}
		schedule = new int[M];
		for(int city = 0; city < M; city++) schedule[city] = scanner.nextInt();
	}
	
	static void solution() {
		for(int city = 1; city <= N; city++) dfs(city, city);
		String answer = isPossibleSchedule();
		System.out.println(answer);
	}
	
	static void dfs(int start, int city) {
		canVisit[start][city] = true;
		for(int near : map.get(city)) {
			if(!canVisit[start][near]) dfs(start, near);
		}
	}
	
	static String isPossibleSchedule() {
		for(int index = 0; index < M - 1; index++) {
			if(!canVisit[schedule[index]][schedule[index + 1]]) return "NO";
		}
		return "YES";
	}
	
	public static void main(String[] args) {
		input();
		solution();
	}
	
	static class Reader {
		BufferedReader br;
		StringTokenizer st;
		public Reader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {
			while(st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}
		int nextInt() {
			return Integer.parseInt(next());
		}
	}
}
profile
자바, 웹 개발을 열심히 공부하고 있습니다!

0개의 댓글