#include<cstdio>
#include<ctime>
#include<cstdlib>
#include<stack>
char map[10][15] = { 0 };
void printfmap(char *pmap,int imax,int jmax) {
printf("\n-------------------------------------------------\n");
for (int i = 0; i < imax; i++) {
for (int j = 0; j < jmax; j++) {
if (pmap[i*jmax + j] == 1)
printf("*");
else if (pmap[i*jmax + j] == 0)
printf(" ");
else
printf("%c",pmap[i*jmax + j]);
}
printf("\n");
}
printf("-------------------------------------------------\n");
}
void makemap(char *pmap, int imax, int jmax) {
for (int i = 0; i<imax; i++)
for (int j = 0; j < jmax; j++) {
if (rand() % 3 == 1)
pmap[i*jmax + j] = 1;
}
}
typedef struct {
int fangxiang;
int i;
int j;
}E;
using std::stack;
stack<E> estack;
E next(E pre) {
switch (pre.fangxiang) {
case 0:
pre.j++; break;
case 1:
pre.i++; break;
case 2:
pre.j--; break;
case 3:
pre.i--; break;
}
pre.fangxiang = 0;
return pre;
}
bool ise(char * pmap,int imax,int jmax,const E &e) {
if (e.i<0 || e.i>=imax || e.j<0 || e.j>=jmax)
return false;
if (pmap[e.j + e.i*jmax] == 0)
return true;
else
return false;
}
void foot(char *pmap,int imax,int jmax, const E &e) {
pmap[jmax*e.i + e.j] = 'O';
}
void cantfoot(char *pmap, int imax, int jmax, const E &e) {
pmap[jmax*e.i + e.j] = 'X';
}
void jie(char * pmap, int imax, int jmax, const E &start,const E &end) {
E dq,tmp;
dq = start;
do {
if (ise(pmap, imax, jmax, dq)) {
estack.push(dq);
foot(pmap,imax,jmax,dq);
if (dq.i == end.i&&dq.j==end.j)break;
dq = next(dq);
}
else {
if (!estack.empty())
{
tmp = estack.top();
estack.pop();
}
while (!estack.empty()&&tmp.fangxiang==3)
{
cantfoot(pmap, imax, jmax, tmp);
tmp = estack.top();
estack.pop();
}
if (tmp.fangxiang < 3) {
tmp.fangxiang++;
estack.push(tmp);
}
printf("tmp i=%d j=%d fangxiang=%d\n", tmp.i, tmp.j, tmp.fangxiang);
dq = next(tmp);
}
} while (!estack.empty());
}
int main() {
srand(time(NULL));
makemap((char*)map, 10, 15);
map[0][0] = 0;
map[9][14] = 0;
printfmap((char*)map, 10, 15);
E start;
start.i = 0;
start.j = 0;
start.fangxiang = 0;
E end;
end.i = 9;
end.j = 14;
jie(&map[0][0], 10, 15, start, end);
printfmap((char*)map, 10, 15);
getchar();
return 0;
}