【算法学习】二、深度优先搜索与广度优先搜索

来源:互联网 发布:网络安全产品有哪些 编辑:程序博客网 时间:2024/05/23 22:31

<1>如何用深度优先搜索解决上一篇中提到的问题,即 ABC + DEF = GHI 将1-9分别填入9个字母中。

#include <stdio.h>int a[10],book[10],total=0;void dfs(int step){    int i;    if (step==10)    {    if (a[1]*100+a[2]*10+a[3] + a[4]*100+a[5]*10+a[6] == a[7]*100+a[8]*10+a[9])    {        total++;        printf("%d%d%d + %d%d%d = %d%d%d\n",a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9]);    }    return;    }    for (i=1; i<=9; i++) {        if (book[i]==0) {            a[step]=i;            book[i]=1; // 表示数字i已经用过            dfs(step+1);              book[i]=0; // 将刚刚尝试的数字i收回        }    }    return;}int main() {    dfs(1);    printf("共有%d种",total/2);    return 0;}

<2>寻找陆地问题,在一个n*m的方格中,0表示海洋,1表示陆地,随机选择一块陆地作为开始点,求这块陆地占地面积(多少个格子)
1>广度优先搜索

#include <stdio.h>struct note{    int x; // x表示横坐标    int y; // y表示纵坐标};int main(){    struct note que[2501]; // 假设n<=50    int head,tail;    int a[51][51];    int book[51][51]={0}; // 用来标记某一点是否走过    int i,j,k,sum,max=0,mx,my,n,m,startx,starty,tx,ty;    // 定义一个方向数组    int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};    // 读入n行,m列的地图,及开始点坐标    scanf("%d%d%d%d",&n,&m,&startx,&starty);    // 读入地图    for (i=1; i<=n; i++)        for (j=1; j<=m; j++) {            scanf("%d",&a[i][j]);        }    // 队列初始化    head = 1;    tail = 1;    // 将起始点坐标入队    que[tail].x = startx;    que[tail].y = starty;    tail++;    book[startx][starty] = 1; // 将该店标记置为1    sum = 1;    // 当队列不为空时循环    while (head < tail) {        // 枚举右下左上4个方向        for (k=0; k<=3; k++) {            // 得到下一步的坐标            tx = que[head].x + next[k][0];            ty = que[head].y + next[k][1];            // 判断是否越界            if (tx<1 || tx>n || ty<1 || ty>m) {                continue;            }            // 判断是否是陆地,是否已走过            if (a[tx][ty]==1 && book[tx][ty]==0) {                sum++;                book[tx][ty] = 1;                // 将该点入队                que[tail].x = tx;                que[tail].y = ty;                tail++;            }        }        head++;// 将队列中已判断完的点出队    }    printf("这片陆地有%d个格子\n",sum);    return 0;}
0 0
原创粉丝点击