迷宫问题

来源:互联网 发布:与男闺蜜滚床单 知乎 编辑:程序博客网 时间:2024/06/06 18:53
#include <stdio.h>#include <stdlib.h>#define n 5#define m 5/*地图*/char place[m][n] = {'.', '.', '.', '*', '*','*', '.', '*', '*', '.','.', '.', '.', '.', '.','.', '.', '.', '.', '.','*', '.', '.', '.', '.'};/*定义起始坐标 与 终点坐标*/int xStart = 0;int yStart = 0;int xEnd = 2;int yEnd = 0;/*最大拐弯次数*/int maxCount = 2;/*定义走的方向*/int a[5][2] = {0, 0, -1, 0, 0, -1, 0, 1, 1, 0};int change = 0;int oldDriection = 0;int flag;int ok(int x, int y) {if (x < 0 || x >= m || y < 0 || y >=n || place[x][y] == '*')return 0;return 1;}void traceback(int x, int y) {if (change > maxCount+1)return;if (flag)return;if (x == xEnd && y == yEnd) {flag = 1;return;}for (int d = 1; d<=4; d++) {x+=a[d][0];y+=a[d][1];int temp = oldDriection;if (ok(x, y)) {if (d != oldDriection)change++;oldDriection = d;traceback(x, y);oldDriection = temp;if (d != oldDriection)change--;}x-=a[d][0];y-=a[d][1];}}int main() {traceback(xStart, yStart);if (flag)printf("yes");else printf("no");return 0;}

0 0
原创粉丝点击