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

/*
* 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++;
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值