迷宫求解

maze.txt

1 1 1 1 1 1 1 1 1 1 
1 1 1 1 1 1 1 1 1 1
0 0 0 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1 1 1
1 1 0 0 0 0 0 1 1 1
1 1 0 1 1 1 0 1 1 1 
1 1 0 1 1 1 0 1 1 1 
1 1 0 1 1 1 0 1 1 1 
1 1 0 0 1 1 0 1 1 1 
1 1 1 0 1 1 1 1 1 1
maze.h

#pragma once 
#include <iostream>
#include <assert.h>
#include <ctype.h>
#include<stdlib.h>
#include <stack>
using namespace std;
#pragma warning(disable:4996)
#define IN "maze.txt"
#define N 10

typedef struct Pos
{
	int row;
	int col;
}Pos;
void getMaze(int *maze, int len);
void printMaze(int *maze, int len);
void getPath(int *maze, Pos entry);

maze.cpp

#include "maze.h"

void getMaze(int *maze, int len)
{
	FILE *fp = fopen(IN, "r");
	char c;
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			c = fgetc(fp);
			if (c == '0' || c == '1')
			{
				maze[i*N + j] = c - '0';
			}
			else if (isspace(c))
			{
				j--;
			}
			else if (c == EOF)
			{
				cout << "迷宫缺失" << endl;
				exit(EXIT_FAILURE);
			}
		}
	}
}
void printMaze(int *maze, int len)
{
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			cout << maze[i*N + j]<<" ";
		}
		cout << endl;
	}
	cout << endl;
}

bool findWay(int *maze ,Pos cur)
{
	if (cur.row >= 0 && cur.row < 10 && cur.col < 10 && cur.col >= 0 &&
		(maze[cur.row*N + cur.col] == 0))
		return true;
	else
	return false;
}

void getPath(int *maze, Pos entry)
{
	stack<Pos> a;
	Pos cur, next;
	cur = next = entry;
	a.push(cur);
	while (!a.empty())  //找到出口
	{
		maze[cur.col + cur.row*N] = 2;
		if (cur.row != entry.row && cur.col != entry.col &&
			(cur.row == 9 || cur.row == 0 || cur.col == 0 || cur.col == 9))
		{
			return;   
		}                                          
		//进行上下左右的探测

		next = cur;
		next.col++;
		if (findWay(maze, next))
		{
			cur = next;
			a.push(cur);
			continue;
		}

		next = cur;
		next.row++;
		if (findWay(maze, next))
		{
			cur = next;
			a.push(cur);
			continue;
		}

		next = cur;
		next.row--;
		if (findWay(maze, next))
		{
			cur = next;
			a.push(cur);
			continue;
		}
	
		next = cur;
		next.col--;
		if (findWay(maze, next))
		{
			cur = next;
			a.push(cur);
			continue;
		}
		cur = a.top();
		a.pop();
	}	
}
main.cpp

#include "maze.h"

void test()
{
	int arr[N][N];
	getMaze((int *)arr, N);
	printMaze((int *)arr,N);
	Pos entry = { 2, 0 };
	getPath((int *)arr,entry);
	printMaze((int *)arr, N);
}

int main()
{
	test();
	return 0;
}

	//int arr[N][N] = {0};
	memset(arr, 0, sizeof(arr));
	//int *p = (int *)arr;
	//for (int i = 0; i < N; i++)
	//{
	//	for (int j = 0; j < N; j++)
	//	{
	//		cout << p[i*N+j] << " ";  //memset 与 直接赋值0 有什么区别 
	//	}
	//	cout << endl;		
	//}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值