1. 程式人生 > >迷宮小遊戲實現

迷宮小遊戲實現

 一.首先給出一個迷宮

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 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1 1 1
1 1 0 0 0 0 0 0 1 1
1 1 0 1 1 1 1 0 1 1
1 1 0 1 1 1 1 0 1 1

1 1 0 1 1 1 1 1 1 1

二.迷宮路徑為


三.實現想法

1,首先給出初始位置,遍歷其位置的上下左右,如果為0則表是可以走通,如果為一則表示沒有通路。

2,走到分岔路口時,選擇一條通路,繼續前行。如果此路不通,則返回到分岔路口處選擇另一通路繼續前行,如果每條分叉路口都不通,則返回到初始位置,列印沒有通路。選擇下一個位置是否為通條件是:位置合法和此位置為0.

3,儲存走過的路線,給每條走過的路賦值2。

四,開始時,要fopen 檔案讀取儲存在檔案中的地圖,讀取完畢後腰fclose檔案。

五,程式碼實現

#pragma once
#define N 10


#include<stack>
#include<assert.h>
#include<iostream>


using namespace std;


struct Pos
{
int _row;//行
int _col;//列
};


void GetMaza(int* a, int n)//讀取地圖
{
FILE* fout = fopen("Maza.log", "r");
assert(fout);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n;)
{
char ch = fgetc(fout);
if (ch == '0' || ch == '1')
{
a[i*n + j] = ch - '0';
++j;
}
else
{
continue;
}
}
}
fclose(fout);
}


bool CheakIsAccess(int* a, int n, Pos next)
{
assert(a);
if (next._row >= 0 && next._row < n
&&next._col >= 0 && next._col < n
&&a[next._row*n + next._col] == 0)//行列都合法且下一個為0路通
{
return true;
}
else
return false;
}


bool MazaPath(int* a, int n, const Pos& entry, stack <Pos>& path)
{
Pos next;
Pos cur = entry;
path.push(cur);
while (!path.empty())
{
if (cur._row == n - 1)
{
return true;
}
a[cur._row*n + cur._col] = 2;


next = cur;
next._col++;
if (CheakIsAccess(a, n, next))
{
cur = next;
path.push(cur);
continue;
}

next = cur;
next._row--;
if (CheakIsAccess(a, n, next))
{
cur = next;
path.push(cur);
continue;
}


next = cur;
next._col--;
if (CheakIsAccess(a, n, next))
{
cur = next;
path.push(cur);
continue;
}


next = cur;
next._row++;
if (CheakIsAccess(a, n, next))
{
cur = next;
path.push(cur);
continue;
}

cur = path.top();
path.pop();
}
return false;
}
void PrintMaza(int* a, int n)
{
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
cout << a[i*n + j] << " ";
}
cout << endl;
}
cout << endl;
}
void TestMaze()
{
int a[N][N] = {};
GetMaza((int *)a, N);
PrintMaza((int *)a, N);
//MazaPath((int *)a, N);
stack<Pos>path;
Pos entry = { 2, 0 };
bool ret = MazaPath((int *)a, N, entry, path);
cout << "是否有通道?" << ret << endl;
PrintMaza((int *)a, N);
}

主函式

#define _CRT_SECURE_NO_WARNINGS 1
#include"Maza.h"
int main()
{
TestMaze();
system("pause");
return 0;
}

六,執行結果