NYOJ 58 最少步數(BFS)

來源:互聯網
上載者:User

標籤:

                      最少步數

 

描述

這有一個迷宮,有0~8行和0~8列:

 1,1,1,1,1,1,1,1,1
 1,0,0,1,0,0,1,0,1
 1,0,0,1,1,0,0,0,1
 1,0,1,0,1,1,0,1,1
 1,0,0,0,0,1,0,0,1
 1,1,0,1,0,1,0,0,1
 1,1,0,1,0,1,0,0,1
 1,1,0,1,0,0,0,0,1
 1,1,1,1,1,1,1,1,1

0表示道路,1表示牆。

現在輸入一個道路的座標作為起點,再如輸入一個道路的座標作為終點,問最少走幾步才能從起點到達終點?

(註:一步是指從一座標點走到其上下左右相鄰座標點,如:從(3,1)到(4,1)。)

輸入
第一行輸入一個整數n(0<n<=100),表示有n組測試資料;
隨後n行,每行有四個整數a,b,c,d(0<=a,b,c,d<=8)分別表示起點的行、列,終點的行、列。
輸出
輸出最少走幾步。
範例輸入
23 1  5 73 1  6 7
範例輸出
1211


 1 #include<cstdio> 2 #include<queue> 3 #include<cstring> 4 using namespace std; 5 int sx,sy,ex,ey; 6 int d[4][2]={1,0,0,1,-1,0,0,-1}; 7 bool visit[9][9]; 8  9 int G[9][9]=10 {11     1,1,1,1,1,1,1,1,1,12     1,0,0,1,0,0,1,0,1,13     1,0,0,1,1,0,0,0,1,14     1,0,1,0,1,1,0,1,1,15     1,0,0,0,0,1,0,0,1,16     1,1,0,1,0,1,0,0,1,17     1,1,0,1,0,1,0,0,1,18     1,1,0,1,0,0,0,0,1,19     1,1,1,1,1,1,1,1,1,20 };21 22 struct point23 {24     int x;25     int y;26     int step;27 };28 29 int bfs()30 {31     point init;32     init.x=sx;33     init.y=sy;34     init.step=0;35     queue<point>q;36     q.push(init);37     while(!q.empty())38     {39         point node=q.front();40         q.pop();41         if(node.x==ex&&node.y==ey)42         return node.step;43         for(int i=0;i<4;i++)44         {45             point newnode;46             newnode.x=node.x+d[i][0];47             newnode.y=node.y+d[i][1];48             newnode.step=node.step+1;49             if(!G[newnode.x][newnode.y]&&visit[newnode.x][newnode.y])50             q.push(newnode);51             visit[node.x][node.y]=false;52         }53     }    54 }55 56 int main()57 {58     //freopen("in.txt","r",stdin);59     int t;60     scanf("%d",&t);61     while(t--)62     {63         memset(visit,true,sizeof(visit));64         scanf("%d%d%d%d",&sx,&sy,&ex,&ey);65         int ans=bfs();66         printf("%d\n",ans);67     }68     return 0;69 }               

 

NYOJ 58 最少步數(BFS)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.