1. 程式人生 > >【Uva - 10047 】The Monocycle(搜尋,bfs記錄狀態)

【Uva - 10047 】The Monocycle(搜尋,bfs記錄狀態)

題幹:

Uva的題目就不貼上題幹了,,直接上題意吧。

有你一個獨輪車,車輪有5種顏色,為了5中顏色的相對位置是確定的。有兩種操作:1.滾動:輪子必須沿著順時針方向滾動,每滾動一次會到達另一個格子,著地的顏色會改變(順時針轉)。例如當前是綠色著地下一次就是黑色,依次是紅藍白。2.轉動:就是改變了輪子的方向(不改變顏色),轉動每次只能選擇左轉90度或者右轉90度,即不能掉頭。車子每向前走一格(滾動)耗時1秒,拐彎(轉動)耗時1秒。

開始時方向朝北,輪子接觸地面的顏色為綠色,求出一條耗時最短的路線,到達終點時,使得車子接觸地面的也為綠色,方向無所謂。

解題報告:

   題意解釋清楚了就是個簡單的bfs了,,,只是需要記錄的東西比較多,,之前最多就是考慮個方向,比如這題

【HDU - 1254 】推箱子 (雙bfs),現在再加個顏色的記錄就是了。。vis[x][y][方向][顏色]。

AC程式碼:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define ll long long
#define pb push_back
#define pm make_pair
#define fi first
#define se second
using namespace std;
const int MAX = 2e5 + 5;

struct Node {
	int x,y;
	int dir,col,time;
	Node(){}
	Node(int x,int y,int dir,int col,int time):x(x),y(y),dir(dir),col(col),time(time){}
} st,ed;
int n,m;
char maze[55][55];
int nx[4]= {0,-1,0,1};//左,上,右,下 
int ny[4]= {-1,0,1,0};
bool vis[55][55][5][5];
bool ok (int x,int y) {
	if(x >= 1 && x <= n && y >= 1 && y <=m) return 1;
	return 0 ;
}
int bfs() {
	memset(vis,0,sizeof vis);
	vis[st.x][st.y][1][0] = 1;
	queue<Node> q;
	q.push(st);
	int tx,ty,tc,td;
	while(!q.empty()) {
		Node cur = q.front();q.pop();
		if(cur.x == ed.x && cur.y == ed.y && cur.col == 0) return cur.time;
		tc = (cur.col + 1) % 5;
		tx = cur.x + nx[cur.dir];ty = cur.y + ny[cur.dir];
		if(ok(tx,ty) && maze[tx][ty] != '#' && vis[tx][ty][cur.dir][tc] == 0) {
			vis[tx][ty][cur.dir][tc] = 1;
			q.push(Node(tx,ty,cur.dir,tc,cur.time+1));
		}
		td = (cur.dir + 1) % 4;
		if(vis[cur.x][cur.y][td][cur.col] == 0) {
			vis[cur.x][cur.y][td][cur.col] = 1;
			q.push(Node(cur.x,cur.y,td,cur.col,cur.time+1));
		} 
		td = (cur.dir - 1 + 4) % 4;
		if(vis[cur.x][cur.y][td][cur.col] == 0) {
			vis[cur.x][cur.y][td][cur.col] = 1;
			q.push(Node(cur.x,cur.y,td,cur.col,cur.time+1));
		}
	}
	return -1;
}
int main()
{
	int iCase = 0;
	while(~scanf("%d %d",&n,&m)) {
		if(n == 0 && m == 0) break;
		for(int i = 1; i<=n; i++) {
			scanf("%s",maze[i]+1);
		}
		for(int i = 1; i<=n; i++) {
			for(int j = 1; j<=m; j++) {
				if(maze[i][j] == 'S') st = Node(i,j,1,0,0);
				if(maze[i][j] == 'T') ed = Node(i,j,0,0,0);
			}
		}
		
		if(iCase) puts("");
		printf("Case #%d\n",++iCase);
		int ans = bfs();
		if(ans == -1) puts("destination not reachable");
		else printf("minimum time = %d sec\n",ans);
	}
	return 0 ;
 }

總結:

   程式碼的書寫告訴我們這題只需要一個queue就可以了,,如果不這麼寫的話可能需要一個pq才可以、、比如你把轉向和前進算在算在一步當中然後time+2,那就需要pq了、、