(UVA) The Party, Part I - Solution

I used Breadth-First Search to solve this problem.


import java.io.*;
import java.util.*;

class Main {
    public static HashMap<Integer, ArrayList<Integer>> adjList;
    public static int[] giovanniNumber;
   
    public static void bfs(int start, int numPeople) {
        Queue<GNumber> queue = new ArrayDeque<GNumber>();
        GNumber gn = new GNumber(start, 0);
        queue.add(gn);
       
        HashSet<Integer> addedToQueue = new HashSet<Integer>();
        addedToQueue.add(start);
       
        while (queue.size() > 0) {
            GNumber curr = queue.poll();
            int currPerson = curr.person;
            int currGNumber = curr.gnumber;
           
            giovanniNumber[currPerson] = currGNumber;
           
            ArrayList<Integer> partners = adjList.get(currPerson);
            for (int i = 0; i < partners.size(); i++) {
                if (!addedToQueue.contains(partners.get(i))) {
                    queue.add(new GNumber(partners.get(i), currGNumber+1));
                    addedToQueue.add(partners.get(i));
                }
            }
        }
    }
   
    public static void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
       
        int numCases = sc.nextInt();
        for (int i = 0; i < numCases; i++) {
            if (i > 0) {
                System.out.println();
            }
           
            int numPeople = sc.nextInt();
            int couples = sc.nextInt();
           
            adjList = new HashMap<Integer, ArrayList<Integer>>();
            for (int j = 0; j < numPeople; j++) {
                adjList.put(j, new ArrayList<Integer>());
            }
           
            for (int j = 0; j < couples; j++) {
                int p1 = sc.nextInt();
                int p2 = sc.nextInt();
               
                adjList.get(p1).add(p2);
                adjList.get(p2).add(p1);
            }
           
            giovanniNumber = new int[numPeople];
            bfs(0, numPeople);
           
            for (int j = 1; j < numPeople; j++) {
                System.out.println(giovanniNumber[j]);
            }
        }
                                       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

class GNumber {
    int person;
    int gnumber;
   
    public GNumber(int p, int gn) {
        person = p;
        gnumber = gn;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução