Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- byte[][] graph = new byte[n][n];
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- graph[i][j] = in.nextByte();
- }
- }
- int start = in.nextInt() - 1;
- int finish = in.nextInt() - 1;
- int[] way = new int[n];
- for (int i = 0; i < n; i++)
- way[i] = -1;
- way[start] = -1;
- boolean[] used = new boolean[n];
- LinkedList<Integer> q = new LinkedList<>();
- q.add(start);
- boolean yes = true;
- while (!q.isEmpty()) {
- int x = q.pollFirst();
- for (int i = 0; i < n; i++) {
- if (graph[x][i] == 1 && !used[i]) {
- q.addLast(i);
- way[i] = x;
- used[i] = true;
- }
- }
- }
- int f = 0;
- while (finish != start && f < n + 2) {
- q.addFirst(finish);
- if (way[finish] >= 0)
- finish = way[finish];
- f++;
- }
- if (f == n + 2)
- System.out.println(-1);
- else {
- System.out.println(q.size());
- if (q.size() != 0) {
- System.out.print(start+1);
- while (!q.isEmpty()) {
- System.out.print(" " + (q.pollFirst() + 1));
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement