CF1063B 【Labyrinth】

一道锻炼代码能力的好题

只要bfs一下,向四个方向搜索,剪下枝,就A了(好像还跑的蛮快?)

Code:

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
#include <bits/stdc++.h>

#define check(x, y) (x >= 0 && x < n && y >= 0 && y < m)//判断是否越界

const int MaxN = 2010;
const int dx[] = {0, 1, -1, 0}, dy[] = {-1, 0, 0, 1};//bfs方向数组

struct p
{
int x, y;
int cntx, cnty;
};

int ans;

int n, m, x, y, limx, limy;

std::string s[MaxN];

int vis[MaxN][MaxN];

int disx[MaxN][MaxN], disy[MaxN][MaxN];

void bfs(int x, int y)
{
memset(disx, 0x3f, sizeof(disx));
memset(disy, 0x3f, sizeof(disy) );
std::queue<p> q;
q.push((p){x, y, 0, 0});
disx[x][y] = disy[x][y] = 0;
while (!q.empty())
{
p tmp = q.front();
q.pop();
x = tmp.x, y = tmp.y;
for (int i = 0; i <= 3; i++)
{
int nx = x + dx[i], ny = y + dy[i];
if (!check(nx, ny) || s[nx][ny] == '*')//当前位置是否合法
continue;
int cntx = tmp.cntx + bool(dy[i] == -1), cnty = tmp.cnty + bool(dy[i] == 1);//计算向左/右走步数
if (cntx < std::min(disx[nx][ny], limx + 1) || cnty < std::min(disy[nx][ny], limy + 1))//判断,剪枝
{
disx[nx][ny] = cntx;
disy[nx][ny] = cnty;//更新向左/右走步数
q.push((p){nx, ny, cntx, cnty});

}
}
}
}

int main()
{
scanf("%d%d", &n, &m);
scanf("%d%d", &x, &y), --x, --y;
scanf("%d%d", &limx, &limy);
for (int i = 0; i < n; i++)
std::cin >> s[i];
bfs(x, y);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (disx[i][j] <= limx && disy[i][j] <= limy)
++ans;//统计答案
printf("%d\n", ans);
return 0;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×