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 1maze.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;
//}
399

被折叠的 条评论
为什么被折叠?



