无向图的广度优先遍历

无向图的广度优先遍历通过队列来实现,广度优先队列可以用来实现查找最短路径,也就是距离两个点之间边最少的路径,先让顶点进队列,然后出队列,把和顶点相连通的点入队列,借助队列的先入先出特性来实现广度优先遍历。寻找路径的API如下:(Graph 请看前面无向图的邻接表实现)
BreadthFirstPaths(Graph G, int s) 在G中找出所有起点为s的路径
boolean hasPathTo(int v) 是否存在从s到v的一天路径
Iterable pathTo(int v) s到v的路径,如果不存在则返回null

public class BreadthFirstParhs{
	private int[] edgeTo;                              //从起点到一个顶点的当前路径的最后一个顶点
	private boolean[] marked;                          //判断一个顶点是否已经遍历过
	private int s;                                     //起点
	public BreadthFirstParhs(Graph G,int s){
		marked = new boolean[G.V()];
		this. s = s;
		edgeTo = new int[G.V()];
		bfs(G,s);
	}
	private void bfs(Graph G,int v){
		Queue queue = new Queue();
		marked[v] = true;             //标记起点
		queue.enqueue(v);             //将其加入队列
		while(!queue.isEmpty()){
			int w = queue.dequeue();   //从队列中删除下一节点
			edgeTo[w] = v;             //保存最短路径的最后一条边
			marked[w] =true;           //标记,因为最短路径已加
			queue.enqueue(w);		   //并把它添加到队列中
		}
	}
	public boolean hasPathTo(int v) {
		return marked[v];
	}
	public Iterable pathTo(int v){
		//使用栈来生成路径
		Stack stack = new Stack();
		if(!hasPathTo(v)) return null;
		stack.push(v);
		v = edgeTo[v];
		while(v!=s){
			stack.push(v);
			v = edgeTo[v];
		}
		stack.push(s);
		return stack;
	}


	//下面为用到队列的实现
	public class Queue implements Iterable {
    private Node first;    // beginning of queue
    private Node last;     // end of queue
    private int n;               // number of elements on queue

    // helper linked list class
    private static class Node {
        private Item item;
        private Node next;
    }

    /**
     * Initializes an empty queue.
     */
    public Queue() {
        first = null;
        last  = null;
        n = 0;
    }

    /**
     * Returns true if this queue is empty.
     *
     * @return {@code true} if this queue is empty; {@code false} otherwise
     */
    public boolean isEmpty() {
        return first == null;
    }

    /**
     * Returns the number of items in this queue.
     *
     * @return the number of items in this queue
     */
    public int size() {
        return n;
    }

    /**
     * Returns the item least recently added to this queue.
     *
     * @return the item least recently added to this queue
     * @throws NoSuchElementException if this queue is empty
     */
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        return first.item;
    }

    /**
     * Adds the item to this queue.
     *
     * @param  item the item to add
     */
    public void enqueue(Item item) {
        Node oldlast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (isEmpty()) first = last;
        else           oldlast.next = last;
        n++;
    }

    /**
     * Removes and returns the item on this queue that was least recently added.
     *
     * @return the item on this queue that was least recently added
     * @throws NoSuchElementException if this queue is empty
     */
    public Item dequeue() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        Item item = first.item;
        first = first.next;
        n--;
        if (isEmpty()) last = null;   // to avoid loitering
        return item;
    }

    /**
     * Returns a string representation of this queue.
     *
     * @return the sequence of items in FIFO order, separated by spaces
     */
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this) {
            s.append(item);
            s.append(' ');
        }
        return s.toString();
    } 

    /**
     * Returns an iterator that iterates over the items in this queue in FIFO order.
     *
     * @return an iterator that iterates over the items in this queue in FIFO order
     */
    public Iterator iterator()  {
        return new ListIterator(first);  
    }

    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator implements Iterator {
        private Node current;

        public ListIterator(Node first) {
            current = first;
        }

        public boolean hasNext()  { return current != null;                     }
        public void remove()      { throw new UnsupportedOperationException();  }

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next; 
            return item;
        }
    }


    /**
     * Unit tests the {@code Queue} data type.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        Queue queue = new Queue();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-"))
                queue.enqueue(item);
            else if (!queue.isEmpty())
                StdOut.print(queue.dequeue() + " ");
        }
        StdOut.println("(" + queue.size() + " left on queue)");
    }
}
}

你可能感兴趣的:(java,mathWay,graph)