/*
* File name : maze_BFS.cpp
* Function : 迷宫问题 单条路径DFS求解 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;
}Spot;
#define SIZE 10
Spot sarray[SIZE][SIZE];
typedef struct {
int x;
int y;
}Pos;
Pos store[SIZE * SIZE];
int store_pos = 0;
//int offset[4][2] = {-1,0,0,1,1,0,0,-1};
int offset[4][2] = { { -1,0 },
{ 0,1 },
{ 1,0 },
{ 0,-1 }
};
void DFS(Spot data[][SIZE], 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;
}
DFS(sarray, 0, 0);
for (int i = 0; i < store_pos; i++) {
cout << "( " << store[i].x << " , " << store[i].y << " )" << endl;
}
return 0;
}
void DFS(Spot data[][SIZE], int x, int y) {
int tmpx, tmpy;
data[x][y].mark = 1;
store[store_pos].x = x;
store[store_pos++].y = 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 不越界
&& data[tmpx][tmpy].mark == 0// 未被访问过
&& data[tmpx][tmpy].data == 1
) {
DFS(data, tmpx, tmpy);
}
}
}
经典算法<一>迷宫问题 1.单条路径 DFS求解 C++实现
最新推荐文章于 2024-03-19 12:51:08 发布