一.问题
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
二.分析
这个问题可以使用广度优先搜索来求解。
三.C++实现
1.SLabyrinth.h
#ifndef SLABYRINTH_H
#define SLABYRINTH_H
#include <queue>
#include <stdio.h>
using namespace std;
class SLabyrinth
{
private:
int map[12][12]; //-2墙,0可走
unsigned int first;
unsigned int aim;
queue<int> open;
int n;
public:
SLabyrinth(void);
unsigned int Search();
unsigned int IsCanMove(int x, int y, int *newx, int *newy,int direction);
unsigned int IsUsed(int x, int y);
unsigned int IsAim(int x, int y);
~SLabyrinth(void);
};
#endif
2.SLabyrinth.cpp
#include "./SLabyrinth.h"
SLabyrinth::SLabyrinth()
{
n = 12;
FILE *f;
char str;
if((f = fopen("data1.txt", "r")) != NULL )
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
str = fgetc(f);
if(str == '.')
map[i][j] = 0; //0表示空格
else
map[i][j] = -2; //-2表示墙
}
if (j == n)
{ //换行
str = fgetc(f);
}
}
}
fclose(f);
first = 1*n + 8;
aim = 10*n + 7;
open.push(first);
};
unsigned int SLabyrinth::IsAim(int x, int y)
{//是否为目标点
if ((x == aim/n) && (y = aim%n))
return 1;
return 0;
}
unsigned int SLabyrinth::IsUsed(int x, int y)
{//该点是否用过
if (map[x][y] == 0)
return 0;
return 1;
}
unsigned int SLabyrinth::IsCanMove(int x, int y, int *newx, int *newy, int direction)
{//是否可以移动,并将新点保存至newx,newy
int tempx = x;
int tempy = y;
switch (direction)
{
case 0:
tempx--; //left
break;
case 1:
tempy++; //down
break;
case 2:
tempx++; //right
break;
case 3:
tempy--; //up
break;
}
*newx = tempx;
*newy = tempy;
if (tempx < 0 || tempx >= n || tempy < 0 || tempy >= n)
return 0;
if (map[tempx][tempy] == 0)
return 1;
return 0;
}
unsigned int SLabyrinth::Search()
{//BFS
int u;
int x;
int y;
int num;
int newx;
int newy;
map[first/n][first%n]=1;
while (!open.empty())
{
u = open.front();
open.pop();
x = u / n;
y = u % n;
num = map[x][y];
path.push(u);
for (int i = 0; i < 4; i++)
{
if (IsCanMove(x, y, &newx, &newy, i))
{
if(IsAim(newx, newy))
return num;
if(!IsUsed(newx, newy))
{
map[newx][newy] = num + 1;
open.push(newx*n + newy);
}
}
}
}
}
SLabyrinth::~SLabyrinth()
{
}
3.Test.cpp
#include "SLabyrinth.h"
#include <iostream>
using namespace std;
void main()
{
SLabyrinth SLy;
cout<<SLy.Search()<<endl;
}
4.data1.txt
XXXXXXXXXXXX
X......X.XXX
X.X.XX.....X
X.X.XX.XXX.X
X.X.....X..X
X.XXXXXXXXXX
X...X.X....X
X.XXX...XXXX
X.....X....X
XXX.XXXX.X.X
XXXXXXX..XXX
XXXXXXXXXXXX