您的位置:首页 > 编程语言 > C语言/C++

经典算法<一>迷宫问题 2.单条路径 BFS求解 C++实现

2016-05-13 08:35 746 查看
/*
* File name  : maze_DFS.cpp
* Function   : 迷宫问题 2.单条路径BFS求解 C++实现
* Created on : 2016年5月12日
* Author     : beijiwei@qq.com
* Copyright  : 欢迎大家和我一起交流学习,转载请保持源文件的完整性。
任何单位和个人不经本人允许不得用于商业用途
*
题目:迷宫问题(1): 只有一条通道的迷宫
0为墙,1为通道

入口
1 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 1 1 1 1 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 1 0 1 1 1 1 0 0
0 0 1 0 1 0 0 1 0 0
0 0 1 1 1 0 0 1 1 0
0 0 0 0 0 0 0 0 1 1
出口

*
*/
#include <cstdio>
#include <iostream>

#pragma warning(disable:4996)

using namespace std;

typedef struct {
int data;
bool mark;
int x;
int y;
}Spot;

#define SIZE 10
Spot sarray[SIZE][SIZE];

Spot spot_queue[SIZE *SIZE];
int  head=-1 ;
int  tail=0 ;

int offset[4][2] = { { -1,0 },
{ 0,1 },
{ 1,0 },
{ 0,-1 }
};

void BFS( int x, int y);

int main(int argc, char** argv)
{
int M = 0, N = 0;

freopen("input.txt", "r", stdin);
cin >> M >> N;

for (int i = 0; i<M; i++)
for (int j = 0; j < N; j++) {
cin >> sarray[i][j].data;  // get input data
sarray[i][j].mark = 0;
sarray[i][j].x = i;
sarray[i][j].y = j;
}

BFS(0, 0);

for (int i = 0; i < tail; i++) {
cout << "( " << spot_queue[i].x << " , " << spot_queue[i].y << " )" << endl;
}

return 0;
}

void BFS(int x, int y) {
int tmpx, tmpy;

sarray[x][y].mark = 1;
spot_queue[tail++] = sarray[x][y];//原点入队
head++;

while (head != tail) {
x = spot_queue[head].x;//取出头部spot 的坐标
y = spot_queue[head].y;
for (int k = 0; k < 4; k++) {
tmpx = x + offset[k][0];
tmpy = y + offset[k][1];
if (tmpx >= 0 && tmpx < SIZE  // x 不越界
&&	tmpy >= 0 && tmpy < SIZE // y 不越界
&&  sarray[tmpx][tmpy].mark == 0// 未被访问过
&& sarray[tmpx][tmpy].data == 1
) {
sarray[tmpx][tmpy].mark = 1;
spot_queue[tail++] = sarray[tmpx][tmpy];//满足条件入队
}
}
head++;
}

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