0
点赞
收藏
分享

微信扫一扫

java的BFS DFS 一般模板

才德的女子 2022-04-14 阅读 161
java

本文章的模板主要用于个人解决图的搜索问题

结点类

class Node{
    private int i, j;

    public Node(int i, int j) {
        this.i = i;
        this.j = j;
    }

    //返回邻接表
    public List<Node> getNextNodes(){
        ArrayList<Node>res=new ArrayList<>();
        //此处为邻接表添加邻接节点

        return res;
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    public int getJ() {
        return j;
    }

    public void setJ(int j) {
        this.j = j;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Node)) return false;
        Node node = (Node) o;
        return getI() == node.getI() && getJ() == node.getJ();
    }

    @Override
    public int hashCode() {
        return Objects.hash(getI(), getJ());
    }

    @Override
    public String toString() {
        return "Node{" +
                "i=" + i +
                ", j=" + j +
                '}';
    }
}

DFS

 public void DFS(Node first){
        LinkedList<Node>stack=new LinkedList<>();
        HashSet<Node>visited=new HashSet<>();
        stack.push(first);
        visited.add(first);
        while (!stack.isEmpty()){
            Node pop = stack.pop();
            //此处对当前遍历到的结点进行操作
            System.out.println(pop);
            
            List<Node> nextNodes = pop.getNextNodes();
            for (Node nextNode : nextNodes) {
                if (visited.add(nextNode))
                    stack.push(nextNode);
            }
        }
    }

BFS

public void BFS(Node first){
        LinkedList<Node>queue=new LinkedList<>();
        HashSet<Node>visited=new HashSet<>();
        queue.add(first);
        visited.add(first);
        while (!queue.isEmpty()){
            Node remove = queue.remove();
            //此处对当前遍历到的结点进行操作
            System.out.println(remove);

            List<Node> nextNodes = remove.getNextNodes();
            for (Node nextNode : nextNodes) {
                if (visited.add(nextNode))
                    queue.add(nextNode);
            }
        }
    }

上述的结点类是二维特征,如有其他情况可以进行修改,如果需要寻找路径,则需要为Node结点添加前驱结点,最后请根据需求完善**getNextNodes()**方法。
visited是用于标记已访问结点的,如果结点的特征比较简单,可以修改为数组(比如上面的二维特征),从而能够降低时间复杂度,本文章主要用于个人使用,如有问题可以留言。

举报

相关推荐

0 条评论