[Update] to be applied first search depth and breadth-first search algorithm

Depth-first search

1. Definitions

Depth-first search algorithm (English: Depth-First-Search, DFS) is an algorithm for traversing or searching a tree or graph. Traversing the tree node depth along the tree branch as deep as possible in the search tree. Where node v When both sides have been exploring, the search will find back to the originating node of the edge piece of node v. This process continues until all the nodes have been found so far reachable from the source node. If there is a node undetected, one is selected as the source node and the process is repeated, the whole process is repeated until all nodes have been visited so far. It belongs to the blind search.

Depth-first search is a classic graph theory algorithms using depth-first search algorithm can generate the appropriate target topology map sorting table, the use of topological sorting table can easily solve many problems related to graph theory, such as the maximum path problems, etc.

2. Applications

Example 1

There are n items, each item of the weight w [i], the value of c [i]. Now you need to select a plurality of items placed in a backpack capacity V, so that the article is selected from the backpack weight and without exceeding the volume V, so that the value of the item and the maximum backpack, seeking the most value. (1≤n≤20)

If the idea of ​​using DFS algorithm to solve this question, we need to consider each item can be viewed as a node, and this question may constitute a special number (starting from the root, there is only one node of each layer) , by recursively traversing the depth of each node, and then to exhaust all possible arrangements, a last update a feature value.

C ++ language:

#include<iostream>
using namespace std;

#define maxn 30
int n,v;
int maxvalue=0;
int w[maxn], c[maxn];

/*
函数会一直递归调用下去,只要index没有到达n,如果到达n,则说明所有物品的岔路都已经穷举完了
每次新添加一个物品,都会生成新的岔路,每个岔路有两个选择,即是否将当前物品添加到背包
递归结束,会有2^n个方案,其中满足总容量<v且价值超出历史最大价值时,更新当前最大价值
*/
void dfs(int index,int sumv,int sumvalue) {
    //递归终止条件
    if(index == n) {
        if(sumv<=v&&sumvalue>maxvalue) {
            maxvalue = sumvalue;
        }
        return ;
    }
    dfs(index+1,sumv,sumvalue);
    dfs(index+1,sumv+w[index],sumvalue+c[index]);
}

/*
对上面的实现进行"剪枝"优化,即每次进行岔路选择的时候,如果添加当前物品到背包中会超出容量v
则不添加该物品
经过优化以后,所有的岔路方案都是总容量不超出v的方案
*/
void dfs2(int index,int sumv,int sumvalue) {
    if(index == n) {
        if(sumvalue>maxvalue) {
            maxvalue = sumvalue;
        }
        return ;
    }
    dfs(index+1,sumv,sumvalue);
    if(sumv+w[index]<=v)
        dfs(index+1,sumv+w[index],sumvalue+c[index]);
}
int main() {

    scanf("%d%d",&n,&v);

    for(int i =0; i<n; i++) {
        scanf("%d",&w[i]);
    }
    for(int i =0; i<n; i++) {
        scanf("%d",&c[i]);
    }
    dfs(0,0,0);
    printf("最大价值为:%d",maxvalue);
    return 0;
}

Input:

5 8
3 5 1 2 2
4 5 2 1 3

Output:

最大价值为:10

3. Summary

pending upgrade

BFS

1. Definitions

Breadth-first search algorithm (English: Breadth-First-Search, abbreviated BFS), also translated as breadth-first search or breadth-first search is a graph search algorithm. Simply put, the BFS is starting from the root, traversing node of the tree along the width of the tree. If all nodes are accessed, the algorithm is aborted.

2. Applications

Example 1

Gives a m * n matrix, the matrix element is 0 or 1. He said position (x, y) with its up and down four positions (x, y + 1), (x, y-1), (x + 1, y), (x-1, y) are adjacent. If there are several matrix 1 is adjacent (not necessarily adjacent two by two), then call these 1 constitutes a "block." Compute the number of "blocks" of a given matrix.
0,111,001
0.01 million
0000100
0001110
1110100
1111000

E.g., a matrix of 6 × 7 above, the number of "block" is 4.

#include<iostream>
#include<queue>
using namespace std;
const int maxn = 100;
int m,n;
struct node {
    int x,y;
};

int matrix[maxn][maxn];
bool inq[maxn][maxn] = {false};
int X[4] = {0,0,1,-1};
int Y[4] = {1,-1,0,0};
bool judge(int x,int y) {
    if(x>=m||x<0||y>=n||y<0)
        return false;
    if(matrix[x][y]==0||inq[x][y]==true)
        return false;
    return true;
}

void bfs(int x,int y) {
    queue<node> Q;
    node Node;
    Node.x = x,Node.y = y;
    Q.push(Node);
    while(!Q.empty()) {
        node tmp = Q.front();
        Q.pop();
        //标记该位置相邻的位置
        for(int i =0; i<4; i++) {
            int newx = tmp.x+X[i];
            int newy = tmp.y+Y[i];
            if(judge(newx,newy)) {
                node newnode ;
                newnode.x=newx;
                newnode.y=newy;
                
                Q.push(newnode);
                inq[newx][newy] = true;
            }
        }
    }
}
int main() {
    scanf("%d%d",&m,&n);
    for(int i =0;i<m;i++){
        for(int j=0;j<n;j++){
            scanf("%d",&matrix[i][j]);
        }
    }
    int ans = 0;
    for(int i =0;i<m;i++){
        for(int j=0;j<n;j++){
            if(matrix[i][j]==1&&inq[i][j]==false){
                ans++;
                inq[i][j]=true;
                bfs(i,j);
            }
        }
    }
    printf("%d",ans);
    return 0;
}

Input:

6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0

Output:

4

Example 2

Given a n*msize labyrinth, where *representative of the non-through wall, and. "" Representative flat, S represents a start point, T, represents endpoints. During the move, you can only go up and down the ground four locations. Find the minimum number of steps reaches the end point from the start point T S.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

const int maxn = 100;
struct node {
    int x,y;
    int step;
} S,T,Node;

int n,m;
char maze[maxn][maxn];
bool inq[maxn][maxn] = {false};
int X[4] = {0,0,1,-1};
int Y[4] = {1,-1,0,0};

bool test(int x,int y) {
    if(x>= n||x<0||y>= m||y<0) return false;
    if(maze[x][y] == '*') return false;
    if(inq[x][y] == true) return false;
    return true;
}

int BFS() {
    queue<node> q;
    q.push(S);
    while(!q.empty()) {
        node top = q.front();
        q.pop();
        if(top.x ==T.x&& top.y ==T.y) {
            return top.step;
        }
        for(int i=0; i<4; i++) {
            int newx = top.x +X[i];
            int newy = top.y +Y[i];
            if(test(newx,newy)) {
                Node.x = newx,Node.y = newy;
                Node.step = top.step+1;
                q.push(Node);
                inq[newx][newy] = true;
            }
        }
    }
    return -1;
}

int main() {
    scanf("%d%d",&n,&m);
    for(int i=0; i<n; i++) {
        getchar();
        for(int j=0; j<m; j++) {
            maze[i][j] = getchar();
        }
        maze[i][m+1] = '\0';
    }
    scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y);
    S.step = 0;
    printf("%d",BFS());
    return 0;
}

Input:

5 5
.....
.*.*.
.*S*.
.***.
...T*
2 2 4 3

Output:

11

3. Summary

DFS&BFS

Through the realization of the above examples and code, not difficult to find, DFS is a combination of recursive achieved at the time of writing, it is necessary to consider how the problem can be abstracted into a recursive scenarios, then analyze the recursive termination condition according to the requirements of the subject, and transfer formula

The BFS, needed to achieve binding queues, each time to traverse all nodes of the same level (abstract representations), and then added to the queue according to the order, the time of each cycle, is determined whether the queue is empty, if not empty then the queue head node removed and then the head node corresponding to all the child nodes sequentially queued in the order, until all nodes are queues. Typically require a secondary container to record whether the node through queue.

References:

This paper to be updated, currently only involves thinking and simple application of the algorithm, the latter went on to add two algorithms use ideas in the tree and figure

Guess you like

Origin www.cnblogs.com/ericling/p/11871874.html