递归实现迷宫求解
2016-07-15 22:51
447 查看
首先在当前路径前 有一个maze.txt,保存的内容为
头文件 maze.h
maze.cpp
用来测试 的 main函数 main.cpp
代码写的可谓是逼格非常低啊。暂时这样吧,以后有空来修改。
0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 0
头文件 maze.h
#pragma once #define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> #include<assert.h> #define MAX_WID 10 #define MAX_LEN 10 #define FILENAME "maze.txt" int Getseat(FILE*stream); struct seat { int x; int y; }; class maze { public: seat entry; maze(); ~maze(); void Init(); void printmaze(); //bool PathMaze(seat entry); bool pathMaze(seat entry); bool IsPass(seat entry); private: int _maze[MAX_WID][MAX_LEN]; };
maze.cpp
#include"maze.h" FILE* fp = fopen(FILENAME, "r"); int tmp[MAX_WID][MAX_LEN] = { 0 }; maze::maze() { Init(); entry.x = 9; entry.y = 8; for (int i = 0; i < MAX_LEN; i++) { for (int j = 0; j < MAX_WID; j++) { tmp[i][j] = _maze[i][j]; } } } int Getseat(FILE*stream) { assert(stream); while (1) { int c = getc(stream); if ((c != ' ') && (c != '\n') && (c != EOF)) return c-'0'; } } void maze::Init() { if (fp == NULL) { perror(FILENAME); exit(EXIT_FAILURE); } for (int i = 0; i < MAX_LEN;i++) { for (int j = 0; j < MAX_WID; j++) { _maze[i][j] = Getseat(fp); } } } void maze::printmaze() { for (int i = 0; i < MAX_LEN; i++) { for (int j = 0; j < MAX_WID; j++) { std::cout <<" "<<tmp[i][j]; } std::cout << '\n'; } } bool maze::IsPass(seat entry) { if (tmp[entry.x][entry.y] == 1) return true; return false; } //先进去再判断的解法 bool maze::pathMaze(seat entry) { if (entry.x < 0 || entry.y < 0 || entry.y == MAX_WID) { std::cout << "ok" << std::endl; return true; } if (IsPass(entry)) { tmp[entry.x][entry.y] = 2; // 超前 seat newEntry1(entry); newEntry1.x -= 1; if (pathMaze(newEntry1)) { return true; } seat newEntry2(entry); newEntry2.y -= 1; if (pathMaze(newEntry2)) { return true; } seat newEntry3(entry); newEntry3.y += 1; if (pathMaze(newEntry3)) { return true; } tmp[entry.x][entry.y] = 3; } return false; } maze::~maze() { fclose(fp); }
用来测试 的 main函数 main.cpp
#include"maze.h" int main() { maze m1; m1.printmaze(); int c=m1.pathMaze(m1.entry); m1.printmaze(); system("pause"); return 0; }
代码写的可谓是逼格非常低啊。暂时这样吧,以后有空来修改。
相关文章推荐
- java基础笔记很实用
- 8086 CPU 寄存器简介
- 机器学习实战 - 读书笔记(06) – SVM支持向量机
- 第1个linux命令——echo
- 19.Which two statements about the background process of the database writer are true? (Choose two.)
- nginx 配置虚拟目录并支持php
- Linux下安装ncurces
- 美图功能ios源代码
- SQL
- 训练第六天
- Hangman Judge
- PHP Calendar API方法归纳总结
- Socket
- 堆(heap)排序算法
- LRU Cache
- MYSQL基础笔记(二)-SQL基本操作
- Android基础知识--BroadcastReceiver
- 线程安全及重入函数
- 18.View the Exhibit and identify the component marked with a question mark.
- LVS+keepalived实现负载均衡