在迷宫里面找到出口
#include <stdio.h>
#include <stdlib.h>
/*
-1 障碍物
0 空白
1 可以走的路线
*/
#define MAX_ROW 9
#define MAX_COLUMN 9
int datas[9][9] ={
-1, 0, -1, -1, -1, -1, -1, -1, -1,
0, 0, 0, 0, 0, -1, -1, -1, -1,
0, -1, -1, -1, 0, -1, -1, -1, -1,
-1, -1, 0, -1, 0, -1, -1, -1, -1,
-1, -1, -1, 0, 0, -1, -1, -1, -1,
-1, -1, -1, 0, -1, -1, -1, 0, -1,
-1, -1, -1, 0, -1, -1, -1, 0, -1,
-1, -1, -1, 0, 0, 0, 0, 0, -1,
-1, -1, -1, -1, -1, -1, -1, 0, 0
};
/**
左右上下顺序进行搜索
return 小于0:上个点应该重置为不可用
*/
int tryFind(int x, int y) {
int notBlockPoint = -1;
if (x == 2 && y== 0) {
printf("xxx\n");
}
if(datas[x][y] == 1) {
//已经找过的点
return -1;
}
if(datas[x][y] == 0) {//可用的点,设置成已经找过的点
//printf("set x %d y %d", x, y);
datas[x][y] = 1;
}else {//不可达点,返回
//printf("unset x %d y %d", x, y);
return -1;
}
if(x == MAX_ROW - 1 && y == MAX_COLUMN - 1) {
return 1;
}
if(y == 0){ //第1列不需要向坐找了
}else {
if (tryFind(x, y-1) > 0){
notBlockPoint = 1;
}
}
if(y == MAX_COLUMN - 1){//最后一列不需要向右
}else{
if(tryFind(x, y+1) > 0){
notBlockPoint = 1;
}
}
if(x == 0) {
}else {
if(tryFind(x-1, y) > 0){
notBlockPoint = 1;
}
}
if(x == MAX_ROW - 1) {
}else{
if(tryFind(x+1, y) > 0){
notBlockPoint = 1;
}
}
if(notBlockPoint < 0) {
datas[x][y] = 0;
}
printf("end x%d y%d \n", x, y);
return notBlockPoint;
}
int main()
{
printf("Hello world!\n");
tryFind(0, 1);
int i, j;
for(i=0; i< MAX_ROW; i++) {
for(j=0; j<MAX_COLUMN; j++){
if(datas[i][j] == -1) {
printf("=");
}else if(datas[i][j] == 1) {
printf(">");
}else{
printf(" ");
}
if(j == MAX_COLUMN - 1){
printf("\n");
}
}
}
return 0;
}
转载于:https://blog.51cto.com/483181/1925977