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

经典算法<一>迷宫问题 4.多条路径 求路径条数求解 C++实现

2016-05-18 15:19 831 查看
/*
* File name  : maze_dual_path.cpp
* Function   : 迷宫多条路径求解     C++实现
* Created on : 2016年5月14日
* Author     : beijiwei@qq.com
* Copyright  : 欢迎大家和我一起交流学习,转载请保持源文件的完整性。
任何单位和个人不经本人允许不得用于商业用途

说明:
1.第一条通路打通前,将不能到达的节点变为墙(0),分叉点变为 -1
2.第一次到达出口后,开始逆推,判断节点是否在打通的回路上,若是则 path增加1,遇到分叉点,分拆点变为1
3.本程序只能求 path 总数,待优化
*/
#include <cstdio>
#include <iostream>

#pragma warning(disable:4996)

using namespace std;

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

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

Spot cross_store[20];
int  cross_cursor = -1;

void find(int x, int y, int fx, int fy);
int  path_count = 0;

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].x = i;
sarray[i][j].y = j;
sarray[i][j].mark = false;
}
find(0, 0,0,0);
cout<< "path count is : " << path_count << endl;

return 0;
}

int get_pass_count(int x, int y)
{
int tmpx, tmpy, count = 0;
int offset[4][2] = { -1,0,0,1,1,0,0,-1 };

for (int k = 0; k < 4; k++) {
tmpx = x + offset[k][0];
tmpy = y + offset[k][1];
if (tmpx >= 0 && tmpx < SIZE &&
tmpy >= 0 && tmpy < SIZE &&
sarray[tmpx][tmpy].data == 1 &&
sarray[tmpx][tmpy].mark == false
)
{
count++;
}
}
return count;
}

bool is_connect_to_path(int x, int y, int fx, int fy)
{
int tmpx, tmpy, count = 0;
int offset[4][2] = { -1,0,0,1,1,0,0,-1 };

for (int k = 0; k < 4; k++) {
tmpx = x + offset[k][0];
tmpy = y + offset[k][1];
if (tmpx >= 0 && tmpx < SIZE &&
tmpy >= 0 && tmpy < SIZE &&
sarray[tmpx][tmpy].data == -1 &&
sarray[tmpx][tmpy].mark == true
)
{
if (!(tmpx == fx && tmpy == fy))
count++;
}
}
return (count >0) ? true : false;
}

bool get_first_flag = false;

void find(int x, int y,int fx, int fy)
{
int tmpx, tmpy, count = 0;
int offset[4][2] = { -1,0,0,1,1,0,0,-1 };
sarray[x][y].mark = true;
cout << x << "  " << y << endl;

if (get_first_flag == true && is_connect_to_path(x, y,fx,fy))
{
path_count++;
}

if (x == 9 && y == 9)
{
path_count++;
get_first_flag = true;
sarray[x][y].data = -2;
}

count = get_pass_count(x, y);
if (count == 0) // no road
{
sarray[x][y].data = 0;
}
if(count > 1 ) // set cross  data to -1
{
sarray[x][y].data = -1;
}

if (count > 0)
{
for (int k = 0; k < 4; k++) {
tmpx = x + offset[k][0];
tmpy = y + offset[k][1];
if (tmpx >= 0 && tmpx < SIZE &&
tmpy >= 0 && tmpy < SIZE &&
sarray[tmpx][tmpy].data == 1 &&
sarray[tmpx][tmpy].mark == false
)
{
find(tmpx,tmpy,x,y);
}
}

if (get_pass_count(x, y) == 0)
{
sarray[x][y].data = 0;
}
}

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