分类: C/C++
2008-04-16 11:55:17
#include
#include
#include
// 0表示路径为通, -1表示路径为不通
int a[10][10] = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, -1, -1, -1, -1, -1, -1, -1, 0, 0},
{0, 0, 0, 0 ,0, 0, 0, 0, 0, 0},
{0, -1,-1, -1, -1, -1, -1, -1, -1, -1},
{0, -1, 0, 0, 0, 0, 0, 0, 0, -1},
{0, -1, 0, 0, 0, 0, 0, 0, 0, -1},
{0, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, -1, 0, 0 ,0, 0, 0, 0, -1, 0},
{0, -1, 0, -1, 0, 0, 0, 0, -1, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
int maze[10][10];
int move(int pos_i, int pos_j, int prepos_i, int prepos_j);
int main() {
printf("before: \n");
for(int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
printf("%d\t", a[i][j]);
}
printf("\n");
}
move(0, 0, 0, 0);
printf("\nmaze: \n");
for(int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
printf("%d\t", maze[i][j]);
}
printf("\n");
}
getchar();
return 0;
}
int move(int pos_i, int pos_j, int prepos_i, int prepos_j) {
if(pos_i < 0 || pos_i >9 || pos_j < 0 || pos_j >9) { //check array overflow
return 0;
}
if(maze[prepos_i][prepos_j]+1>maze[pos_i][pos_j] &&maze[pos_i][pos_j] >0 || a[pos_i][pos_j] == -1) { //如果路不通 或者 这种方案到达该地的步数大于以前某种方案的步数(非最优方案)
return 0;
}
maze[pos_i][pos_j] = maze[prepos_i][prepos_j]+1; //记录到达该地的步数,然后分别发散移动
move(pos_i-1, pos_j, pos_i, pos_j);
move(pos_i, pos_j+1, pos_i, pos_j);
move(pos_i+1, pos_j, pos_i, pos_j);
move(pos_i, pos_j-1, pos_i, pos_j);
return 1;
}