简体   繁体   中英

Recursive Backtracking in simple graph

imagine the following simple graph:

图形

Every entity has an index starting count 0 (so A has index 0, B has index 1 and so on).

A and B are connected, so the distance between them is 1, so fe the distance between A and D is 2, because they are both connected with F.

How to implement a method in java, that takes two indices and a distance as parameters, and performs a recursive backtracking in order to find out whether the two given entities are reachable within the given distance ???

So, if I call the method with parameters (3, 0, 2), then it should return true, because 3 is D and 0 is A and the distance between them is 2, so it's true.

What I've tried:

public boolean backtracking(int index0, int index1, int d) {

    boolean reachable = relation[index0][index1];

    if (d > 0 && !reachable) {
        for (int i = index0+1; i <= index1+d; i++) {
            backtracking(index0+1, index1, d-1);
        }
    }

    return reachable;
}

I have an adjacency-matrix with the relations inside the 2D-boolean-array relation, based on the graph.

Thanks in advance

The following code does what you want.

The canReach methods is a recursive method. If the allowed distance is smaller than zero, then we return false. If the node given to canReach is equal to this, then it is reachable. Otherwise, iterate over the neighbours of the Node with the distance decreased by 1.

Code:

public class Node {
    private Set<Node> neighbours = new HashSet<Node>();

    public Node() {
    }

    public void connect(Node node) {
        if (neighbours.add(node))
            node.connect(this);
    }

    public boolean canReach(Node node, int distance) {
        if (distance < 0)
            return false;
        if (this.equals(node)) {
            return true;
        } else {
            for (Node neighbour : neighbours)
                if (neighbour.canReach(node, distance - 1))
                    return true;
            return false;
        }
    }
}

private Graph() {
    Node a = new Node();
    Node b = new Node();
    Node c = new Node();
    Node d = new Node();
    Node e = new Node();
    Node f = new Node();
    a.connect(b);
    b.connect(c);
    b.connect(e);
    a.connect(f);
    f.connect(d);
    System.out.println(a.canReach(d, 2));

}

public static void main(String[] args) {
    new Graph();
}

Output:

false
true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM