Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.LinkedList;
- import java.util.Queue;
- public class Main {
- public static void BFS(HashMap<String, Vertax> graph, String vertax) {
- Queue<String> queue = new LinkedList<String>();
- queue.add(vertax);
- graph.get(vertax).flag = true;
- while (!queue.isEmpty()) {
- String value = queue.poll();
- System.out.print(value + " ");
- Vertax v = graph.get(value);
- Iterator<String> iter = v.next.iterator();
- while (iter.hasNext()) {
- String next_value = iter.next();
- if (graph.get(next_value).flag == false) {
- queue.add(next_value);
- graph.get(next_value).flag = true;
- }
- }
- }
- }
- public static void main(String[] args) {
- HashMap<String, Vertax> graph = new HashMap<String, Vertax>();
- try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
- String line;
- while ((line = br.readLine()) != null) {
- String[] tokens = line.split(" ");
- String value = tokens[0];
- Vertax vertax = new Vertax(value);
- graph.put(value, vertax);
- for (int i = 1; i < tokens.length; i++) {
- vertax.next.add(tokens[i]);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- BFS(graph, "A");
- }
- }
- class Vertax {
- String value;
- boolean flag;
- LinkedList<String> next;
- public Vertax(String value) {
- this.value = value;
- this.flag = false;
- next = new LinkedList<String>();
- }
- }
- /* inputs on console of eclipse
- A B S
- B A
- C D E F S
- D C
- E C H
- F C G
- G S H
- H E G
- S A C G
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement