標籤: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;}