#include <iostream>
#include <conio.h>
void main()
{
/*int A[100] = {
7,8,9,15,16,17,20,
28,35,19,22
};
int B[100]=
{
-1,0,0,0,
1,1,2,3,4,4,
7
};
int len = 11;
int i = len-1;
while (i != -1)
{
std::cout<< A[i] <<" ";
i = B[i];
}*/
//寻路
const int w = 10;
const int h = 10;
const int s = w * h;
int map[s] =
{
1,1,1,1,1,1,1,1,1,1,
1,0,0,1,0,0,0,0,0,1,
1,0,0,1,0,0,0,0,0,1,
1,0,0,0,1,0,0,0,0,1,
1,0,0,0,1,0,0,0,0,1,
1,0,0,0,0,0,0,1,0,1,
1,0,0,0,1,0,1,0,0,1,
1,0,1,0,0,1,0,0,0,1,
1,1,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1
};
int startx = 1;
int starty = 1;
int endx = w-2;
int endy = h-2;
//存储道路
int path[s]={};
int pathlen = 0;
while (1)
{
system("cls");
pathlen = 0;
//寻路
if (map[startx+starty*w] == 0 &&
map[endx+endy*w] == 0)
{
int A[s];
int B[s];
int len = 0;
//把起点装入A表,-1装入B表
A[len] = startx + starty* w;
B[len] = -1;
len++;
//1 2 3
// \|/
//0- -4
// /|\
//7 6 5
int xx[] = {-1,-1,0,1,1,1,0,-1};
int yy[] = {0,-1,-1,-1,0,1,1,1};
/*int xx[] = {-1,0,1,0};
int yy[] = {0,-1,0,1};*/
//循环A表,并发散
for (int i = 0;i < len; ++i)
{
//发散A[i]的八个方向,P
for (int k = 0; k < 8; ++k)
{
int nx = A[i]%w+xx[k];
int ny = A[i]/w+yy[k];
//P不能出界,P不能是障碍,P不在A表
if (nx < 0 || nx > w-1 ||
ny < 0 || ny > h-1)
continue;
if (map[nx + ny * w] == 1)
continue;
bool inA = false;
for (int i = 0;i < len; ++i)
{
if (A[i] == nx + ny * w)
{
inA = true;
break;
}
}
if (inA)
continue;
// 则P可以存入A表中,i存入B表中
A[len] = nx + ny * w;
B[len] = i;
len++;
//如果P就是终点
if (nx == endx && ny == endy)
{
int ii = len-1;
while (ii != -1)
{
path[pathlen++] = A[ii];
ii = B[ii];
}
i = len;
break;
}
}
}
}//-------------寻路结束------------
//绘图
int temp[s] = {};
for (int i = 0;i < s; ++i)
temp[i] = map[i];//0空地 1障碍
for (int i = 0; i < pathlen; ++i)
temp[ path[i] ] = 2;//2路径
temp[startx + starty * w] = 3;//3起点
temp[endx + endy * w] = 4;//4终点
for (int i = 0;i < s; ++i)
{
switch(temp[i])
{
case 0:std::cout<<"□";break;
case 1:std::cout<<"■";break;
case 2:std::cout<<"●";break;
case 3:std::cout<<"起";break;
case 4:std::cout<<"终";break;
}
if (i % w == w - 1)
std::cout<<"\n";
}
int a = _getch();
if (a == 'w') starty--;
if (a == 's') starty++;
if (a == 'a') startx--;
if (a == 'd') startx++;
if (a == 'i') endy--;
if (a == 'k') endy++;
if (a == 'j') endx--;
if (a == 'l') endx++;
}
}