脚本宝典收集整理的这篇文章主要介绍了java 实现 图的广度优先搜索,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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}; breathFirstSeArch(n1, 5); } 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.print(n + " "); n.visited = true; if(n.val == x) System.out.println("Find "+n); queue.enqueue(n); } } } }
}
value: 2 value: 3 value: 5 Find value: 5value: 4
代码出处:http://codecloud.net/top-10-algorithms-for-coding-interview-447.html
以上是脚本宝典为你收集整理的java 实现 图的广度优先搜索全部内容,希望文章能够帮你解决java 实现 图的广度优先搜索所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。