真题解析 Two Tank Move

Posted proscientist

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了真题解析 Two Tank Move相关的知识,希望对你有一定的参考价值。

题目大意:

N*M的矩阵,有坦克a和b,终点c和d,坦克a需要走到c,坦克b需要走到d。

每经过一秒,坦克可以选择周围的8个方向任意移动一步,也可以选择原地不动。

但是两个坦克不能相邻(周围8个方向),也不能去有墙的地方

问,最少需要多少秒,才能使两个坦克都达到目的地

 

题解:BFS,只是状态数有81个

 

 1 #include <stdio.h>
 2 #define MAX 26
 3 #define MAXDIR 9
 4 int dy[] = { 0, 1, 1, 1, 0, -1, -1, -1, 0 };
 5 int dx[] = { 1, 1, 0, -1, -1, -1, 0, 1, 0 };
 6 int data[MAX][MAX];
 7 int map[MAX][MAX][MAX][MAX];
 8 int T, M, N, ans, front, rear;
 9 int sy1 = 0, sx1 = 0, sy2 = 0, sx2 = 0;
10 int ey1 = 0, ex1 = 0, ey2 = 0, ex2 = 0;
11 struct Node{
12     int y1, x1, y2, x2;
13 }queue[400000], out;
14 
15 bool canPlace(int y, int x){
16     if (y < 0 || y >= N || x < 0 || x >= M || data[y][x] < 0)return false;
17     return true;
18 }
19 
20 bool isAdjacent(int y1, int x1, int y2, int x2){
21     int y, x;
22     for (int i = 0; i < MAXDIR; ++i){
23         y = dy[i] + y1, x = dx[i] + x1;
24         if (canPlace(y, x) && y == y2 && x == x2)return true;
25     }
26     return false;
27 }
28 
29 int bfs(){
30     front = rear = 0;
31     map[sy1][sx1][sy2][sx2] = 0;
32     queue[rear++] = { sy1, sx1, sy2, sx2 };
33     int y1, x1, y2, x2;
34     while (front != rear){
35         out = queue[front++];
36         for (int i = 0; i < MAXDIR; ++i){
37             y1 = dy[i] + out.y1, x1 = dx[i] + out.x1;
38             if (!canPlace(y1, x1))continue;
39             for (int j = 0; j < MAXDIR; ++j){
40                 y2 = dy[j] + out.y2, x2 = dx[j] + out.x2;
41                 if (!canPlace(y2, x2) || map[y1][x1][y2][x2] >= 0 || isAdjacent(y1, x1, y2, x2))continue;
42                 map[y1][x1][y2][x2] = map[out.y1][out.x1][out.y2][out.x2] + 1;
43                 if (map[ey1][ex1][ey2][ex2] >= 0) return map[ey1][ex1][ey2][ex2];
44                 queue[rear++] = { y1, x1, y2, x2 };
45             }
46         }
47     }
48     return -1;
49 }
50 
51 int main(void){
52 //    freopen("sample_input.txt", "r", stdin);
53     scanf("%d", &T);
54     for (int tc = 1; tc <= T; ++tc){
55         scanf("%d%d", &N, &M);
56         for (int i = 0; i < N; ++i)
57         for (int j = 0; j < M; ++j){
58             scanf("%d", &data[i][j]);
59             if (data[i][j] == 1)sy1 = i, sx1 = j;
60             if (data[i][j] == 2)sy2 = i, sx2 = j;
61             if (data[i][j] == 3)ey1 = i, ex1 = j;
62             if (data[i][j] == 4)ey2 = i, ex2 = j;
63             for (int m = 0; m < N; ++m)
64             for (int n = 0; n < M; ++n)
65                 map[i][j][m][n] = -1;
66         }
67         printf("#%d %d\n", tc, bfs());
68     }
69     return 0;
70 }

 

以上是关于真题解析 Two Tank Move的主要内容,如果未能解决你的问题,请参考以下文章

设计模式—静态代理模式(聚合与继承方式比较)

乘风破浪:LeetCode真题_002_Add Two Numbers

蓝桥真题——2021年蓝桥python组省赛真题+解析+代码(通俗易懂版)

乘风破浪:LeetCode真题_021_Merge Two Sorted Lists

Navigation Move_base最最全解析(按执行逻辑梳理)

Navigation Move_base最最全解析(按执行逻辑梳理)