CC Chapter 4 Tree and Graph --Graph

来源:互联网 发布:机械臂编程 编辑:程序博客网 时间:2024/05/29 09:14

1. Graphs

A tree is actually a type of graph, but not all graphs are trees. Simply put, a tree is a connected graph without cycles. 

A graph is simply a collection of nodes with edges between (some of) them. 

  • Graphs can be either directed or undirected. While directed edges are like a one-way street, undirected edges are like a two-way street. 
  • The graph might consist of multiple isolated subgraphs. If there is a path between every pair of vertices, it is called a connected graph. 
  • The graph can also have cycles(or not). An "Acyclic graph" is one without cycles. 

Representation

(1) Adjacency List

Every vertex stores a list of adjacent vertices. In an undirected graph, an edge like (a, b) store twice. once in a's adjacent vertices and once in b's adjacent vertices.

class Graph{       public Node[] nodes;}class Node{       public String name;       public Node[] children;}


(2) Adjacency Matrices

An adjacency matrix is an N* N boolean matrix( where N is the number of nodes), where a true value at matrix[i][j] indicates an edge from node i to node j. (or 0s and 1s)


2. Graph Search

DFS(depth-first search): start at root, explore each branch completely before moving onto the next branch. Go deep first we go wide.

BFS(Breadth -first search): start at root, and explore each neighbor before going on to any of their children. Go wide before we go deep.

void DFS(Node root){       if(root == null) return;       visit(root);       root.visited = true;       foreach(Node n in root.adjacent){             if(n.visited == false){                  DFS(n);             }       }}

void BFS(Node root){       Queue queue = new Queue();       root.marked = true;       queue.enqueue(root); //add to the end of queue       while(!queue.isEmpty()){             Node r = queue.dequeue(); //remove from the front of the queue            visit(r);            foreach(Node in r.adjacent){                     if(n.marked == false){                          n.marked = true;                          queue.enqueue(n);                     }           }       }}


Bidirectional Search : find the shortest path between a source and destination node. It operates by essentially running two simultaneous breath-first searches, one from each node. When their searches collide, we have found a path. 

 



 

0 0
原创粉丝点击