(UVA) The mysterious X network - 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 bfs(int start, int end) {
        Queue<Camarade> queue = new ArrayDeque<Camarade>();
        Camarade c = new Camarade(start, 0);
        queue.add(c);
       
        HashSet<Integer> addedToQueue = new HashSet<Integer>();
        addedToQueue.add(start);
       
        while (queue.size() > 0) {
            Camarade curr = queue.poll();
            int currCamarade = curr.camarade;
            int currDepth = curr.depth;
           
            if (currCamarade == end) {
                return currDepth-1; // the last one is the guy who will help
            }
           
            ArrayList<Integer> reachCamarades = adjList.get(currCamarade);
            for (int i = 0; i < reachCamarades.size(); i++) {
                int nextCamarade = reachCamarades.get(i);
                if (!addedToQueue.contains(nextCamarade)) {
                    c = new Camarade(nextCamarade, currDepth+1);
                    queue.add(c);
                    addedToQueue.add(nextCamarade);
                }
            }
        }
       
        return 0;
    }
   
    public static void process() throws NumberFormatException, IOException {  
        Scanner sc = new Scanner(System.in);
       
        int numTests = sc.nextInt();
        for (int i = 0; i < numTests; i++) {
            if (i > 0) {
                System.out.println();
            }
            int numCamarades = sc.nextInt();
           
            adjList = new HashMap<Integer, ArrayList<Integer>>();
            for (int j = 0; j < numCamarades; j++) {
                adjList.put(j, new ArrayList<Integer>());  
            }
           
            for (int j = 0; j < numCamarades; j++) {
                int camarade = sc.nextInt();
                int numCamaradesKnown = sc.nextInt();
                for (int k = 0; k < numCamaradesKnown; k++) {
                    int c = sc.nextInt();
                    adjList.get(camarade).add(c);
                }
            }
           
            int seekHelp = sc.nextInt();
            int willHelp = sc.nextInt();
           
            System.out.println(seekHelp + " " + willHelp + " " + bfs(seekHelp, willHelp));
        }
                                                
        return;
    }
  
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();

        System.exit(0);
    }
}

class Camarade {
    int camarade;
    int depth;
   
    public Camarade(int c, int d) {
        camarade = c;
        depth = d;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução