您的位置:首页 > 其它

dfs bfs模板

2015-01-29 15:38 423 查看
#include <set>

#include <iostream>

#include <vector>

#include <algorithm>

#include <stdlib.h>

#include <math.h>

#include <string.h>

#include <queue>

using namespace std;


#define Goal_dfs 2


#define MAX 300



int map[MAX][MAX];

bool visit[MAX][MAX];// 访问标记

int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};// 方向向量




struct data// BFS队列中的状态数据结构

{

int x, y;// 坐标位置

int step;// 搜索步数统计器

}seat[MAX];


void input_dfs(int row, int column)

{

int temp;

for(int i=0; i<row; i++)

for(int j=0; j<column; j++)

{

// if();scanf("%c",&temp);//目标或者起点条件

scanf("%d", &temp);

}

}


void input_bfs()

{}


void initialize(int row, int column)

{

memset(map, 0, sizeof(map) );

memset(visit, false, sizeof(visit) );

for(int i=1; i<=row; i++)

for(int j=1; j<=column; j++)

visit[i][j] = true;

}


bool check_dfs(int x, int y)

{

if(!visit[x][y])return 1;// 满足条件

else return 0;

}


bool check_bfs(data temp)

{

if(visit[temp.x][temp.y])// 满足条件,根据条件添加

return 1;

elsereturn 0;

}


void dfs(int x, int y)

{

visit[x][y] = 1;// 标记该节点被访问过

if(map[x][y] == Goal_dfs)// 出现目标态Goal

{

//();做相应处理

return ;

}


for(int i=0; i<4; i++)

{

if( check_dfs(x+dir[i][0], y+dir[i][1]) )// 按照规则生成下一个节点

dfs(x+dir[i][0],y+dir[i][1]);

}


return ;// 没有下层搜索节点,回溯

}


void bfs(data first)

{

queue<data> que;// BFS队列

data now, next;// 定义2个状态,当前和下一个

first.step = 0;// 计数器清零


que.push(first);

visit[first.x][first.y] = 1;


while(!que.empty() )

{

now = que.front();// 取队首元素进行扩展

/*

if(now = goal)// 出现目标态,此时为Step_Counter的最小值,可以退出即可

{

();// 做相关处理

return ;

}

*/


for(int i=0; i<4; i++)

{

next.x = now.x + dir[i][0];

next.y = now.y + dir[i][1];

next.step = now.step +1;


if(check_bfs(next) )// 如果状态满足约束条件则入队

{

que.push(next);

visit[next.x][next.y] = 1;

}

}

que.pop();// 队首元素出队

}


return ;

}


int main()

{



return 0;

}

[/code]

来自为知笔记(Wiz)

附件列表

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: