First, solve the problem. Then, write the code. ” - John Johnson

It's not at all important to get it right the first time. It's vitally important to get it right the last time. ” - Andrew Hunt and David Thomas

Sunday, September 21, 2014

10959 - The Party, Part I (BFS)

Author : Jisan
Programming language : Java 
Difficulty : Medium
Status : Accepted
Problem number : UVA-10959
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1900

Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.StringTokenizer;

public class TheParty1 {

    public static void main(String[] args) throws Exception {
        InputReader in = new InputReader(System.in);
        int tc = in.nextInt();
        while (tc-- > 0) {
            int n = in.nextInt();
            int m = in.nextInt();
            boolean[][] g = new boolean[n][m];
            for (int i = 0; i < m; i++) {
                int a = in.nextInt();
                int b = in.nextInt();
                g[a][b] = g[b][a] = true;
            }

            int[] dist = new int[n];
            Arrays.fill(dist, -1);
            dist[0] = 0;
            Queue<Integer> Q = new ArrayDeque<Integer>();
            Q.add(0);
            while (!Q.isEmpty()) {
                int i = Q.remove();
                for (int j = 0; j < n; j++)
                    if (g[i][j] && dist[j] == -1) {
                        dist[j] = dist[i] + 1;
                        Q.add(j);
                    }
            }
            for (int i = 1; i < n; i++)
                System.out.println(dist[i]);
            if (tc != 0)
                System.out.println();
        }
    }

    static class InputReader {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

No comments:

Post a Comment