hdu 1175 連連看

來源:互聯網
上載者:User

標籤:bfs

    注意事項:

    (1)只有數字相同的兩個點可以相互消除

    (2)轉折次數不能超過兩次

    (3)數字都為‘0’, ‘0’的不能消除

    (4)兩個座標不能相同

  

    解題思路:

    

//第一組資料3 41 2 3 40 0 0 04 3 2 141 1 3 4

   從開始的點判斷下一步走四個方向中哪些方向是可以走的,可以走的條件是下一步為空白(即‘0’),並且按這種方法走下一步可以使拐彎次數減少

   在這裡將開始的點s,的方向初始化為-1,拐彎次數為-1,其他點的拐彎次數初始化為10

  

      

        綠色箭頭反向為不可以行走的方向,因為如果走的是綠色箭頭這一方向,已經走過一次,要是又走這一方向,不會使拐彎次數減少


#include <iostream>#include <queue>using namespace std;#define MAX 1005struct Node{int x, y, num, dir;//拐彎次數,方向friend bool operator < (Node a, Node b){           return a.num > b.num;//拐彎次數少的點優先考慮}};int dx[]={0,0,-1,1};int dy[]={1,-1,0,0};int v[MAX][MAX], g[MAX][MAX];Node s, e;Node tmp;//記錄拐點int x, y;void Clear(){int i, j;for (i=1; i<=x; i++)  for (j=1; j<=y; j++)    v[i][j] = 10;}int main(){    int i, j, num;Node p, tmp;while (cin>>x>>y && (x||y)){    memset(g, -1, sizeof(g));    for (i=1; i<=x; i++)      for (j=1; j<=y; j++)cin>>g[i][j];    cin>>num;    while (num--)   {      cin>>s.x>>s.y>>e.x>>e.y;      if (g[s.x][s.y]!=g[e.x][e.y] || g[s.x][s.y]==0 ||(s.x==e.x&&s.y==e.y))   cout<<"NO"<<endl;      else      {  Clear(); int flag = 0; priority_queue<Node>q; s.num = s.dir = -1; v[s.x][s.y] = -1; q.push(s); while (!q.empty()){   tmp = q.top();   q.pop();   if (tmp.num==3)break;   if (tmp.x==e.x&&tmp.y==e.y)   {cout<<"YES"<<endl;flag = 1;break;   }  for (i=0; i<4; i++)  {p.x = tmp.x + dx[i];p.y = tmp.y + dy[i];if (g[p.x][p.y]==0||(p.x==e.x && p.y==e.y)){     if (i!=tmp.dir)         p.num = tmp.num + 1;     else p.num = tmp.num;     p.dir = i;     if (p.num<v[p.x][p.y])            {v[p.x][p.y] = p.num;q.push(p);    }}  }}if(flag==0)                   cout<<"NO"<<endl;    } }      }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.