老鼠走迷宫问题,求出所有路径

本次所练习使用的主要方法是递归

所要注意的主要问题是

     要确定起讫点的相对位置,否则又由于递归代码的顺序会漏掉一些可行路径

      先横向/纵向接近目标点,然后再横向/纵向远离目标点(最好对应)

例如: 假设访问的顺序是下上右左(相对于一个固定的矩阵)

2 2 2 2 2 2 2 2 2

2 0 0 0 0 0 0 0 2

2 0 2 2 0 2 2 0 2

2 0 2 0 0 2 0 0 2

2 0 2 0 2 0 2 0 2

2 0 0 0 0 0 2 0 2

2 2 0 2 2 0 2 2 2

2 0 0 0 0 0 0 0 2

2 2 2 2 2 2 2 2 2

可能会忽略黄色所示的路径

2 2 2 2 2 2 2 22

2 0 0 0 0 0 0 0 2

2 0 2 2 0 2 2 0 2

2 0 2 0 0 2 0 0 2

2 0 2 0 2 0 2 0 2

2 0 0 0 0 0 2 0 2

2 2 0 2 2 0 2 2 2

2 0 0 0 0 0 0 0 2

2 2 2 2 2 2 2 22

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int maze[200][200];
pair<int, int> path[500];
int cnt = 1, ptr = -1;//succ=0;
void print(int endpoint){   //three points per row
	printf("No.%d path:\n", cnt++);
	int j = 0;
	for (int num = 0; num <= endpoint;num++){
			printf("(%d, %d)\t", path[num].first, path[num].second);
			j++;
			if (j == 3) {
				printf("\n"); j = 0;
			}
	}
	if(j==3) printf("\n");
}
void visit(int xp, int yp, int xaim, int yaim){
	path[++ptr].first = xp;
	path[ptr].second = yp;
	maze[xp][yp] = 1;
	if (xp == xaim&&yp == yaim) {
		print(ptr);
		//ptr--;   ///it is important not to conduct this step for ptr has been excuted in the following step
		//succ = 1;   
	//	return;
	}
	if (maze[xp ][yp+1] == 0)visit(xp, yp+1, xaim, yaim);
	if (maze[xp +1][yp] == 0)visit(xp+1, yp, xaim, yaim);
	if (maze[xp][yp -1] == 0)visit(xp, yp - 1, xaim, yaim);
	if (maze[xp-1][yp] == 0)visit(xp-1, yp, xaim, yaim);
	//if (succ == false) {
		maze[xp][yp] = 0; 
		ptr--;
	//}
};
int main(){
	ifstream in("input.txt");
	string line;
	int i = 0;
	while (getline(in, line)){
		stringstream ou(line);
		for (int j = 0; ou >> maze[i][j]; j++);
		i++;
	}
	visit(1, 1, 7, 7);
	system("pause");
	return 0;
}

tips:

本代码中用到了文件流,文件中保存的迷宫如以上所述,读者若要检测自己的迷宫的话则要更改代码的相应部分,包括文件流的重新设定和递归顺序的调整(本代码检测的起止点是从左上到右下,其他起止点相对顺序要更改相应的递归顺序)

本代码还用到了字符串流

代码中注释掉的部分是在练习过程中出错的部分,仅供参考

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