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

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

	
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/beijiwei/article/details/51444326
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞