CC Chapter 4 Tree and Graph --Graph

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. 

 



 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值