走迷宫问题(求出所有的可能的解)

 
#include "stdio.h"
#define MAX 25//限定处理的最大的行数和列数
int Maze[MAX][MAX];
int row;
int col;
typedef struct {
	int x;
	int y;
}PosType;
PosType end;
void print (int (*a)[MAX]) {
	int i;
	int j;
	for (i = 0;i < row + 2;i++) {
		for (j = 0;j < col + 2;j++) {
			if (a[i][j]  >= 0 ) {
				printf(" %d ",a[i][j]);
			}
			else printf("%d ",a[i][j]);
		}
		printf("\n");
	}
	printf("-------------------\n");
}
void Try (PosType curPos,int curStep) {
	PosType nextPos;
	int i;
	PosType direc[4] = {{0,1},{1,0},{0,-1},{-1,0}};
	for (i = 0;i <=3;i++) {
		nextPos.x = curPos.x + direc[i].x;
		nextPos.y = curPos.y + direc[i].y;
		if (Maze[nextPos.x][nextPos.y] == -1) {
			Maze[nextPos.x][nextPos.y] = ++curStep;
			if (nextPos.x!=end.x || nextPos.y!=end.y) {
				Try (nextPos,curStep);
			}else {
				print(Maze);
			}
			Maze[nextPos.x][nextPos.y] = -1;
			curStep--;
		}
	}
}
int main () {
	int j,i;
	PosType cur = {1,1};
	scanf ("%d%d",&row,&col);//几行,几列。
	end.x = row;
	end.y = col;
	for (i = 1;i <=row;i++) {
		for (j = 1;j <= col;j++) {
			scanf ("%d",&Maze[i][j]);
		}
	}
	for (i = 0;i <= col + 1;i++) {
		Maze[0][i] = 0;
		Maze[row + 1][i] = 0;
	}
	for (j = 1;j <=row;j++) {
		Maze[j][0] = 0;
		Maze[j][col+1] = 0;
	}
	Maze[1][1] = 1;
	Try (cur,1);
	return 0;
}

你可能感兴趣的:(DFS-深度优先搜索)