Java有向图

GraphNode.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javalearning7;

/**
 *
 * @author WEN
 */
public class GraphNode {
    int val;
    GraphNode next;
    GraphNode[] neighbors;
    boolean visited;
    
    GraphNode(int x) {
        val = x;
    }
    
    GraphNode(int x, GraphNode[] n) {
        val = x;
        neighbors = n;
    }
    
    @Override
    public String toString() {
        return "value : " + val;
    }
}

Queue.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javalearning7;

/**
 *
 * @author WEN
 */
public class Queue {
    GraphNode first;
    GraphNode last;
    
    public void enQueue(GraphNode n) {
        if (first == null) {
            first = n;
            last = first;
        } else {
            last.next = n;
            last = n;
        }
    }
    
    public GraphNode deQueue() {
        if (first == null) {
            return null;
        } else {
            GraphNode temp = new GraphNode(first.val, first.neighbors);
            first = first.next;
            return temp;
        }
    }
}
建好了数据结构之后编写测试类Test。

GraphTest.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javalearning7;

/**
 *
 * @author WEN
 */
public class GraphTest {

    public static void main(String[] args) {
        GraphNode n1 = new GraphNode(1);
        GraphNode n2 = new GraphNode(2);
        GraphNode n3 = new GraphNode(3);
        GraphNode n4 = new GraphNode(4);
        GraphNode n5 = new GraphNode(5);

        n1.neighbors = new GraphNode[]{n2, n3, n5};
        n2.neighbors = new GraphNode[]{n1, n4};
        n3.neighbors = new GraphNode[]{n1, n4, n5};
        n4.neighbors = new GraphNode[]{n2, n3, n5};
        n5.neighbors = new GraphNode[]{n1, n3, n4};

        this.breathFirstSearch(n1, 1);
    }

    public static void breathFirstSearch(GraphNode root, int x) {
        if (root.val == x) {
            System.out.println("find in root");
        }
        Queue queue = new Queue();
        root.visited = true;
        queue.enQueue(root);

        while (queue.first != null) {
            GraphNode c = (GraphNode) queue.deQueue();
            for (GraphNode n : c.neighbors) {
                if (!n.visited) {
                    System.out.println(n + "");
                    n.visited = true;
                    if (n.val == x) {
                        System.out.println("Find " + n);
                    }
                    queue.enQueue(n);
                }
            }
        }
    }
}

输出结果:

find in root
value : 2
value : 3
value : 5
value : 4


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值