I - 迷宫问题 SDUT

时间:2019-01-23
本文章向大家介绍I - 迷宫问题 SDUT,主要包括I - 迷宫问题 SDUT使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

I - 迷宫问题 SDUT

定义一个二维数组:

int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
using namespace std;
const int N = 1e2;
struct node
{
    int x, y;
}path[N][N];    //  这题关键是会保存路径!!!!! 一定要是结构体类型!!!!!因为下面用的时候给它赋值的是一个结构体类型的,...
int a[N][N];
bool vis[N][N];
int xx[4] = {1, 0, 0, -1};
int yy[4] = {0, 1, -1, 0};
void print(int i, int j)
{
    if(i == 0 && j == 0)
        return;
    print(path[i][j].x, path[i][j].y);
    printf("(%d, %d)\n", i, j);
}
void bfs()
{
   queue<node> q;
   vis[0][0] = 1;
   struct node t, tp;
   memset(vis, 0, sizeof(vis));
   t.x = 0;
   t.y = 0;
   q.push(t);
   while(!q.empty())
   {
      tp = q.front();
      q.pop();
      if(tp.x==4&&tp.y==4)
      {
         printf("(0, 0)\n");
         print(4, 4);
         return;
      }
      for(int i = 0;i<4;i++)
      {
              t.x = tp.x + xx[i];
              t.y = tp.y + yy[i];
        if(t.x>=0&&t.x<5&&t.y>=0&&t.y<5&&a[t.x][t.y]==0&&vis[t.x][t.y]==0)
        {
              
              vis[t.x][t.y] = 1;
              q.push(t);
              path[t.x][t.y].x = tp.x; ///!!!!!!!!!
              path[t.x][t.y].y = tp.y;  

        }
      }
   }
}


int main()
{
      memset(vis,0,sizeof(vis));
    for(int i = 0; i < 5; i++)
        for(int j = 0; j < 5; j++)
           {
            scanf("%d", &a[i][j]);
           }
    bfs();
    return 0;
}