题解 | #迷宫问题#
迷宫问题
http://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc
#include<stdio.h>
int Ni, Mj;
typedef struct vint_ {
int n;
int dir;//which direction to the next pos
}vint;
vint tonext[5] = { {0,0}, {0,1}, {1,0}, {0,-1}, {-1,0} };//vint used as direction
vint map[10][10];
int ini(vint map[10][10], int* pi, int* pj, int d) {
int leftd = d == 1 ? 4 : d - 1;
int ni = *pi+tonext[leftd].n, nj =*pj+ tonext[leftd].dir;
while (!(ni >= 0 && ni < Ni && nj>=0 && nj < Mj && map[ni][nj].n != 1)) {
leftd=leftd == 4 ? 1 : leftd + 1;
ni = *pi + tonext[leftd].n, nj = *pj + tonext[leftd].dir;
}
map[*pi][*pj].n = 2;
map[*pi][*pj].dir = leftd;
*pi =ni, * pj =nj;
return leftd;
};
int main() {
while (~scanf("%d %d", &Ni, &Mj)) {
for (int i = 0; i < Ni; i++)
for (int j = 0; j < Mj; j++) {
scanf("%d", &map[i][j].n);
//map[i][j].dir = -1;
}
int i = 0, j = 0, d = ini(map, &i, &j, 2);//d,previous pos to this one:E-1:S-2:W-3:N-4
while (!(i == Ni - 1 && j == Mj - 1))
d = ini(map, &i, &j, d);
i = j = 0;
while (!(i == Ni - 1 && j == Mj - 1)) {
printf("(%d,%d)\n", i, j);
int di = tonext[map[i][j].dir].n;
int dj = tonext[map[i][j].dir].dir;
i += di;
j += dj;
}
printf("(%d,%d)\n", Ni - 1, Mj - 1);
}
}