Site Search:

Graph.java with simple dfs traversal

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Graph {
    private Set<Integer> marked = new HashSet<>();
    private Map<Integer, Set<Integer>> neighbors = new HashMap<>();
    private Integer goal;
    private boolean reached;
    private int count = 0;
    public Set<Integer> getPoints() {
        return neighbors.keySet();
    }
    public int size() {
        return getPoints().size();
    }
    public long edgeSize() {
        return neighbors.values().stream().collect(Collectors.summingLong(Set::size))/2;
    }
    public void addEdge(int a, int b) {
        neighbors.computeIfAbsent(a, k -> new HashSet<Integer>()).add(b);
        neighbors.computeIfAbsent(b, k -> new HashSet<Integer>()).add(a);
    }
    
    public void dfsGoalSearch(Integer start, Integer goal) {
        this.goal = goal;
        dfs(start);
    }
    
    public void dfs(Integer v) {
        marked.add(v);
        if(v.equals(goal)) reached = true;
        for(Integer w : neighbors.get(v)) {
            if(!marked.contains(w)) {
                if(reached) {
                    System.out.println(v +"--" + w + "[label=" + count + ", color=blue,penwidth=3.0];");
                }else{
                    System.out.println(v +"--" + w + "[label=" + count + ", color=red,penwidth=3.0];");
                }
                count++;
                dfs(w);
            }
        }
    }
    
    public static void main(String...args) {
        Graph g = new Graph();
        //change the number of points and edges here.
        for(int i = 0; i < 7; i++) {
            g.addEdge(i, i + 1);
            g.addEdge(i, i + 2);
        }
        for(int i = 15; i < 17; i++) {
            g.addEdge(i, i+1);
        }
        g.addEdge(19, 19);
        System.out.println("strict graph {");
        g.neighbors.keySet().stream().forEach(i -> 
                                             {
                                             Stream.of(g.neighbors.get(i)).flatMap(j -> j.stream())
                                                 .forEach(k -> System.out.println(i + "--" + k + ";"));
                                             });
        //change the start point and goal point here
        g.dfsGoalSearch(3, 6);
        System.out.println("}");
        System.out.println("number of points: " + g.size());
        System.out.println("number of edges: " + g.edgeSize());
        System.out.println("can we reach point 6 from 3? " + g.marked.contains(6));
        System.out.println("can we reach point 16 from 3? " + g.marked.contains(16));
        System.out.println("can we reach point 19 from 3? " + g.marked.contains(19));
    }
}