nyoj-58-最少步數

來源:互聯網
上載者:User
最少步數時間限制:3000 ms  |  記憶體限制:65535 KB難度:4
描述

這有一個迷宮,有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<stdio.h>#include<deque>#include<iostream>using namespace std;typedef struct{    int x,y,step;}T;int zou[10]={-1,1,0,0,0,0,-1,1};int fun(T a,T b){    int map[9][9]={  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};    deque<T> q;    T m;    int i;    while(1)    {        if(a.x==b.x&&a.y==b.y)     return a.step;        a.step++;        for(i=0;i<4;i++)        {            m.x=a.x+zou[i];m.y=a.y+zou[i+4];            if(map[m.x][m.y]==0)            {                m.step=a.step;map[m.x][m.y]=1;                q.push_back(m);            }        }        a=q.front(); q.pop_front();    }}int main(){   T a,b;    int n;    scanf("%d",&n);    while(n--)    {        scanf("%d%d%d%d",&a.x,&a.y,&b.x,&b.y);        a.step=0;        printf("%d\n",fun(a,b));    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.