图:
图相关的问题主要集中在深度优先搜索(depth first search)和广度优先搜索(breath first search)。深度优先搜索很简单,广度优先要注意使用queue. 下面是一个简单的用队列Queue实现广度优先搜索。
- public class GraphTest {
- 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);
- }
- }
- }
- }
- }