牛客寒假6-J.迷宮
阿新 • • 發佈:2019-02-05
cpp div struct 普通 next 問題 while truct tps
鏈接:https://ac.nowcoder.com/acm/contest/332/J
題意:
你在一個 n 行 m 列的網格迷宮中,迷宮的每一格要麽為空,要麽有一個障礙。
你當前在第 r 行第 c 列(保證該格子為空)。每次移動你可以向上下左右任意一個方向移動一格,前提是不能走到障礙上,也不能超出迷宮的邊界。
你向左移動的次數不能超過 x 次,向右不能超過 y 次。
問在這種情況下,對於每個格子,是否存在一種移動方案讓你走到它。
輸出有多少個格子存在移動方案讓你走到它。
思路:
BFS 題目數據有點弱,普通bfs都過了。
看博客找到一份hack代碼。
改了一下,感覺還是有點問題。
Vis數組記錄到某個點的左右剩余次數,當新過去的點剩余次數大於舊的,就更新一下,解決因為bfs順序引起的問題。
代碼:
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int MAXN = 1e3 + 10; int Next[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; struct Node { int _x; int _y; int _l; int _r; Node(int x, int y, int l, int r):_x(x), _y(y), _l(l), _r(r){} }; char Map[MAXN][MAXN]; int Vis[MAXN][MAXN][2]; int n, m, sx, sy; int l, r; int main() { cin >> n >> m; cin >> sx >> sy; cin >> l >> r; for (int i = 1;i <= n;i++) { for (int j = 1;j <= m;j++) cin >> Map[i][j]; } queue<Node> que; que.emplace(sx,sy,l,r); Map[sx][sy] = ‘+‘; Vis[sx][sy][0] = l; Vis[sx][sy][1] = r; while (!que.empty()) { Node now = que.front(); for (int i = 0;i < 4;i++) { int tx = now._x + Next[i][0]; int ty = now._y + Next[i][1]; if (tx < 1 || tx > n || ty < 1 || ty > m) continue; if (Map[tx][ty] == ‘*‘) continue; if (i == 1) { if (now._r == 0) continue; Map[tx][ty] = ‘+‘; if (Vis[now._x][now._y][0] > Vis[tx][ty][0] || Vis[now._x][now._y][1] > Vis[tx][ty][1]) { que.emplace(tx, ty, now._l, now._r - 1); Vis[tx][ty][0] = Vis[now._x][now._y][0]; Vis[tx][ty][1] = Vis[now._x][now._y][1] - 1; } } else if (i == 3) { if (now._l == 0) continue; Map[tx][ty] = ‘+‘; if (Vis[now._x][now._y][0] > Vis[tx][ty][0] || Vis[now._x][now._y][1] > Vis[tx][ty][1]) { que.emplace(tx, ty, now._l - 1, now._r); Vis[tx][ty][0] = Vis[now._x][now._y][0] - 1; Vis[tx][ty][1] = Vis[now._x][now._y][1]; } } else { Map[tx][ty] = ‘+‘; if (Vis[now._x][now._y][0] > Vis[tx][ty][0] || Vis[now._x][now._y][1] > Vis[tx][ty][1]) { que.emplace(tx, ty, now._l, now._r); Vis[tx][ty][0] = Vis[now._x][now._y][0]; Vis[tx][ty][1] = Vis[now._x][now._y][1]; } } } que.pop(); } int res = 0; for (int i = 1;i <= n;i++) for (int j = 1;j <= m;j++) if (Map[i][j] == ‘+‘) res++; /* for (int i = 1;i <= n;i++) { for (int j = 1;j <= m;j++) cout << Map[i][j]; cout << endl; } */ cout << res << endl; return 0; }
牛客寒假6-J.迷宮