|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 andalousie 于 2014-2-25 10:01 编辑
Graph_search.cpp
- #include <iostream>
- #include <ctime>
- #include "graph.h"
- using namespace std;
- int main(){
- /** Creates a graph with 12 vertices */
- Graph g1(12);
- /** Adds edges to the graph */
- g1.addEdge(1, 2); g1.addEdge(1, 3);
- g1.addEdge(2, 4); g1.addEdge(3, 4);
- g1.addEdge(3, 6); g1.addEdge(4 ,7);
- g1.addEdge(5, 6); g1.addEdge(5, 7);
- clock_t t1;
- t1 = clock();
- /** Explores all vertices findable from vertex 1 */
- g1.BFS(1, 3);
- float diff = (double)(clock() - t1)/CLOCKS_PER_SEC ;
- std::cout << std::endl << "The time taken for Breadth first search: "<< diff << std::endl;
-
- clock_t t2;
- t2 = clock();
- /** Explores all vertices findable from vertex 1 */
- g1.DFS(1, 3);
- float diff2 = (double)(clock() - t2)/CLOCKS_PER_SEC ;
- std::cout << std::endl << "The time taken for Breadth first search: "<< diff2 << std::endl;
- }
复制代码 graph.h- #if !defined (GRAPH_H)
- #define GRAPH_H
- /************************************************************
- Class Graph represents a Graph [V,E] having vertices V and
- edges E.
- ************************************************************/
- class Graph {
- private:
- int _n; /// n is the number of vertices in the graph
- int ** _A; /// A stores the edges between two vertices
- public:
- Graph(int size = 2);
- ~Graph();
- bool isConnected(int, int);
- void addEdge(int x, int y);
- void BFS(int, int);
- void DFS(int, int);
- };
- #endif
复制代码
graph.cc
stack.h
- #if !defined (STACK_H)
- #define STACK_H
- const int maxStack=16;
- class IStack
- {
- public:
- IStack():_top(0){}
- void push(int i);
- int pop();
- bool isFull () const { return _top >= maxStack; }
- bool isEmpty () const { return _top == 0; }
- private:
- int _arr [maxStack];
- int _top;
- };
- #endif
复制代码 stack.cc
- #include "stack.h"
- #include <cassert>
- #include <iostream>
- void IStack::push (int i)
- {
- assert (_top < maxStack);
- _arr [_top] = i;
- ++_top;
- }
- int IStack::pop ()
- {
- assert (_top > 0);
- --_top;
- return _arr [_top];
- }
复制代码 queue.h
- #if !defined (QUEUE_H)
- #define QUEUE_H
- const int maxPuts=16;
- class Queue
- {
- public:
- Queue();
- int dequeue();
- void enqueue(int x);
- bool isEmpty() { return _putIdx == _getIdx; }
- private:
- int _arr [maxPuts];
- int _putIdx;
- int _getIdx;
- };
- #endif
复制代码 queue.cc
- #include <cassert>
- #include "queue.h"
- Queue::Queue()
- : _putIdx(0),
- _getIdx(0)
- {}
- int Queue::dequeue()
- {
- assert (_getIdx<_putIdx);
- ++_getIdx;
- return _arr [(_getIdx-1) % maxPuts];
- }
- void Queue::enqueue(int x)
- {
- assert (_putIdx<maxPuts+_getIdx);
- _arr [_putIdx % maxPuts]=x;
- ++_putIdx;
- }
复制代码 我刚刚参照书上写了一个DAG的拓扑排序
|
|