FOJ 1205 小鼠迷宫问题

此题利用的是图的广度优先遍历的思想。

先找出最短路径。

然后再从终点递归回朔求解。

 

其实此递归过程可以写成栈,会更加节省时间。

 

下面是我的代码。。。。。

 

#include <iostream> #include <queue> #include <string.h> using namespace std; #define X 100 #define Y 100 #define DISABLE_SIGN -1 #define MOUSEONE_SIGN -2 #define MOUSETWO_SIGN -3 struct Point_Struct { int x; int y; int flag; }; int Map[X+2][Y+2]; void CalcWayNum(int &num,int x,int y,int M1X,int M1Y) { int plusX[] = {0,1,0,-1}; int plusY[] = {1,0,-1,0}; int i; if (x==M1X&&y==M1Y) { num++; return; } for (i=0;i<4;i++) { if (Map[x+plusX[i]][y+plusY[i]] == Map[x][y]-1) CalcWayNum(num, x+plusX[i], y+plusY[i], M1X, M1Y); } } int main() { int plusX[] = {0,1,0,-1}; int plusY[] = {1,0,-1,0}; int x,y,NumOfDisable; int DisX,DisY; int MouseOneX,MouseOneY; int MouseTwoX,MouseTwoY; int i; int BreakFlag; int NumOfWay; int ShortWay; queue<Point_Struct> Queue; Point_Struct Temp_Point,Temp_Point2; while (scanf("%d%d%d", &x,&y,&NumOfDisable)!=EOF) { memset(Map, 0, sizeof(Map)); for (i=0;i<=y+1;i++) { Map[0][i] = DISABLE_SIGN; Map[x+1][i] = DISABLE_SIGN; } for (i=0;i<=x+1;i++) { Map[i][0] = DISABLE_SIGN; Map[i][y+1] = DISABLE_SIGN; } for (i = 0;i<NumOfDisable;i++) { scanf("%d%d", &DisX, &DisY); Map[DisX][DisY] = DISABLE_SIGN; } scanf("%d%d", &MouseOneX, &MouseOneY); scanf("%d%d", &MouseTwoX, &MouseTwoY); Map[MouseOneX][MouseOneY] = MOUSEONE_SIGN; Map[MouseTwoX][MouseTwoY] = MOUSETWO_SIGN; Temp_Point.x = MouseOneX; Temp_Point.y = MouseOneY; Temp_Point.flag = 0; Queue.push(Temp_Point); //广度优先遍历开始 BreakFlag = 0; ShortWay = 0; while (!Queue.empty()) { Temp_Point = Queue.front(); for (i=0;i<4;i++) { if (Map[Temp_Point.x+plusX[i]][Temp_Point.y+plusY[i]] == 0|| Map[Temp_Point.x+plusX[i]][Temp_Point.y+plusY[i]] == MOUSETWO_SIGN) { Map[Temp_Point.x+plusX[i]][Temp_Point.y+plusY[i]] = Temp_Point.flag+1; Temp_Point2.x = Temp_Point.x+plusX[i]; Temp_Point2.y = Temp_Point.y+plusY[i]; Temp_Point2.flag = Temp_Point.flag+1; Queue.push(Temp_Point2); } } Queue.pop(); } Map[MouseOneX][MouseOneY] = 0; NumOfWay = 0; CalcWayNum(NumOfWay, MouseTwoX, MouseTwoY, MouseOneX, MouseOneY); printf("%d/n", Map[MouseTwoX][MouseTwoY]); printf("%d/n", NumOfWay); } return 0; }

你可能感兴趣的:(struct)