zoukankan      html  css  js  c++  java
  • poj3984迷宫问题(bfs打印路径)

    题目链接:http://poj.org/problem?id=3984

    比较简单,我是用string记录每次走的方向,最后输出。

     1 #include<cstdio>
     2 #include<iostream>
     3 #include<queue>
     4 #include<string>
     5 #include<cstring>
     6 using namespace std;
     7 int dir[4][2]={0,1,0,-1,1,0,-1,0};
     8 int vis[5][5];
     9 int pic[5][5];
    10 struct node
    11 {
    12     int x,y;
    13     int parx,pary;
    14     string s;
    15 
    16 };
    17 node now,nex;
    18 int read()
    19 {
    20     for(int i=0;i<5;i++)
    21         for(int j=0;j<5;j++)
    22         if(scanf("%d",&pic[i][j])==EOF) return 0;
    23         return 1;
    24 }
    25 string bfs()
    26 {
    27    queue<node>q;
    28    now.x=0;
    29    now.y=0;
    30    now.s="";
    31    vis[0][0]=1;
    32    q.push(now);
    33    while(!q.empty())
    34    {
    35        now=q.front();
    36        q.pop();
    37        if(now.x==4&&now.y==4) return now.s;
    38        for(int i=0;i<4;i++)
    39        {
    40            nex.x=now.x+dir[i][0];
    41            nex.y=now.y+dir[i][1];
    42            if(nex.x>=0&&nex.x<5&&nex.y>=0&&nex.y<5&&!vis[nex.x][nex.y]&&pic[nex.x][nex.y]==0)
    43            {
    44                vis[nex.x][nex.y]=1;
    45                switch(i)
    46                {
    47                case 0:nex.s=now.s+'0';break;
    48                case 1:nex.s=now.s+'1';break;
    49                case 2:nex.s=now.s+'2';break;
    50                case 3:nex.s=now.s+'3';break;
    51                }
    52                q.push(nex);
    53            }
    54        }
    55    }
    56 }
    57 void print(string s)  //打印路径
    58 {
    59 
    60   int len=s.length();
    61       int x=0,y=0;
    62       printf("(%d, %d)
    ",x,y);
    63   for(int i=0;i<len;i++)
    64   {
    65       x=x+dir[s[i]-'0'][0];
    66       y=y+dir[s[i]-'0'][1];
    67     printf("(%d, %d)
    ",x,y);
    68   }
    69 
    70 }
    71 int main()
    72 {
    73     while(read())
    74     {
    75         memset(vis,0,sizeof(vis));
    76         print(bfs());
    77     }
    78 }
  • 相关阅读:
    图片处理中的Dithering技术
    网络I/O模型
    并发编程(二)
    并发编程(一)
    socket编程(二)
    socket编程(一)
    异常处理
    软件开发规范
    面向对象进阶
    多态与封装
  • 原文地址:https://www.cnblogs.com/yijiull/p/6613249.html
Copyright © 2011-2022 走看看