首页 > 学院 > 开发设计 > 正文

蓝桥杯 2015 决赛 4 穿越雷区

2019-11-11 01:42:59
字体:
来源:转载
供稿:网友

X星的坦克战车很奇怪,它必须交替地穿越正能量辐射区和负能量辐射区才能保持正常运转,否则将报废。 某坦克需要从A区到B区去(A,B区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短? 已知的地图是一个方阵,上面用字母标出了A,B区,其它区都标了正号或负号分别表示正负能量辐射区。 例如: A + - + - - + - - + - + + + - + - + - + B + - + - 坦克车只能水平或垂直方向上移动到相邻的区。 数据格式要求: 输入第一行是一个整数n,表示方阵的大小, 4<=n<100 接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。 A,B都只出现一次。 要求输出一个整数,表示坦克从A区到B区的最少移动步数。 如果没有方案,则输出-1 例如: 用户输入: 5 A + - + - - + - - + - + + + - + - + - + B + - + - 则程序应该输出: 10 资源约定: 峰值内存消耗 < 512M CPU消耗 < 1000ms

简单BFS.

#include <bits/stdc++.h>using namespace std;vector< vector<char> > g;vector< vector<bool> > b;int n;const int dx[] = {1, 0, -1, 0};const int dy[] = {0, 1, 0, -1};struct Node{ int x, y, step;};bool exist(int x, int y){ return x >= 0 && x < n && y >= 0 && y < n;}int main(){ //freopen("in", "r", stdin); scanf("%d/n", &n); string s; g.resize(n); for (int i = 0; i < n; i++) { getline(cin, s); for (int j = 0; j < s.size(); j++) { if (s[j] != ' ') g[i].push_back(s[j]); } } Node A, B; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (g[i][j] == 'A') A.x = i, A.y = j, A.step = 0; } } b.resize(n); for (int i = 0; i < n; i++) b[i].resize(n); queue<Node> q; q.push(A); b[A.x][A.y] = true; while (!q.empty()) { Node node = q.front(); q.pop(); b[node.x][node.y] = true; for (int i = 0; i < 4; i++) { int xx = node.x + dx[i], yy = node.y + dy[i]; if (exist(xx, yy)) { if (b[xx][yy]) continue; if (g[xx][yy] == 'B') { cout << node.step + 1 << endl; return 0; } if (g[xx][yy] != g[node.x][node.y]) { q.push((Node){xx, yy, node.step + 1}); } } } } cout << "-1" << endl;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表