題目:一個機器人在一個矩形的地圖上行走,地圖上有些方形的障礙(1m*1m),
由於機器人有寬度,不能碰到障礙,每次機器人執行一條指令耗費1s時間,
指令包括向前走(1或2或3m),向左轉,向右轉,給定其實位置和方向,
以及目標的位置(方向任意),求最少的移動時間。
分析:圖論、搜索。最短時間,使用bfs求解到達每個點的最短時間即可。
每個位置有四個狀態(對應四個方向),利用bfs求解;
題目中數據給的是地圖中的方塊的數據,我們需要將他轉化成機器人走的點,
即方塊的四個頂點,這裡相鄰的方塊的頂點公用構成(n+1)*(m+1)矩形,
行編號從0到n,列編號從0到m;
說明:注意機器人有寬度不能走邊界上的路徑。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111#include <stdio.h> #include <stdlib.h> #include <string.h> int block_maps[55][55]; int point_maps[55][55]; int moves_maps[55][55][4]; int dxy[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; int get_direct(char str[]) { if (!strcmp(str, "north")) { return 0; }else if (!strcmp(str, "east")) { return 1; }else if (!strcmp(str, "south")) { return 2; }else if (!strcmp(str, "west")) { return 3; }else return -1; } int queue_x[11111]; int queue_y[11111]; int queue_d[11111]; int bfs(int N, int M, int Sx, int Sy, int Sd, int Ex, int Ey) { memset(moves_maps, 0, sizeof(moves_maps)); moves_maps[Sx][Sy][Sd] = 1; queue_x[0] = Sx; queue_y[0] = Sy; queue_d[0] = Sd; int head = 0, tail = 1; while (head < tail) { int x = queue_x[head]; int y = queue_y[head]; int d = queue_d[head]; if (x == Ex && y == Ey) { return moves_maps[x][y][d]-1; } // move for (int s = 1; s <= 3; ++ s) { int new_x = x + dxy[d][0]*s; int new_y = y + dxy[d][1]*s; if (new_x > 0 && new_x < N && new_y > 0 && new_y < M) { int flag = 0; for (int t = 1; t <= s; ++ t) { if (point_maps[x + dxy[d][0]*t][y + dxy[d][1]*t]) { flag = 1; } } if (!moves_maps[new_x][new_y][d] && !flag) { moves_maps[new_x][new_y][d] = moves_maps[x][y][d]+1; queue_x[tail] = new_x; queue_y[tail] = new_y; queue_d[tail] = d; tail ++; } } } // turn left if (!moves_maps[x][y][(d+3)%4]) { moves_maps[x][y][(d+3)%4] = moves_maps[x][y][d]+1; queue_x[tail] = x; queue_y[tail] = y; queue_d[tail] = (d+3)%4; tail ++; } // turn right if (!moves_maps[x][y][(d+1)%4]) { moves_maps[x][y][(d+1)%4] = moves_maps[x][y][d]+1; queue_x[tail] = x; queue_y[tail] = y; queue_d[tail] = (d+1)%4; tail ++; } head ++; } return -1; } int main() { int N, M, Br, Bc, Er, Ec; char direct[10]; while (~scanf("%d%d",&N,&M) && N+M) { for (int i = 0; i < N; ++ i) { for (int j = 0; j < M; ++ j) { scanf("%d",&block_maps[i][j]); } } scanf("%d%d%d%d%s",&Br,&Bc,&Er,&Ec,direct); memset(point_maps, 0 , sizeof(point_maps)); for (int i = 0; i < N; ++ i) { for (int j = 0; j < M; ++ j) { if (block_maps[i][j]) { point_maps[i+0][j+0] = 1; point_maps[i+0][j+1] = 1; point_maps[i+1][j+0] = 1; point_maps[i+1][j+1] = 1; } } } printf("%dn",bfs(N, M, Br, Bc, get_direct(direct), Er, Ec)); } return 0; }
最后
以上就是糟糕帽子最近收集整理的关于UVa 314 - Robot的全部内容,更多相关UVa内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复