標題:穿越雷區
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消耗 < 2000ms
請嚴格按要求輸出,不要畫蛇添足地打印類似:“請您輸入...” 的多餘內容。
基礎的廣搜
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
int n; //地圖大小
char ch[99][99]; //地圖數組
//方向數組
int dx[4] = {0,1,-1,0};
int dy[4] = {1,0,0,-1};
int vis[110][110]; //標記數組,防止一個點走兩遍
struct xy{
int x;
int y;
int step;
};
void bfs(int i,int j){
xy start,temp; //定義兩個結構體變量,用於標記起始位置和隊首位置
start.x = i;
start.y = j;
start.step = 0;
queue<xy> q;
q.push(start);
while(!q.empty()){
temp = q.front(); //取出隊首元素
q.pop();
if(ch[temp.x][temp.y]=='B'){
cout<<temp.step<<endl;
return ;
}
xy next;
for(int i=0;i<4;i++){
int nx = temp.x + dx[i];
int ny = temp.y + dy[i];
if(nx<n && nx>=0 && ny<n && ny>=0 && !vis[nx][ny] && ch[temp.x][temp.y]!=ch[nx][ny]){
next.x = nx;
next.y = ny;
next.step = temp.step + 1;
vis[nx][ny] = 1;
q.push(next);
}
}
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>ch[i][j];
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(ch[i][j]=='A'){
bfs(i,j);
}
}
}
return 0;
}
提供一組數據
20
A + - + + + + + - + - + + + + - + + - +
- - + - + - - + + - - + - - - - + - - -
- + - + + + - + - + - - + + + - + + - -
- - + - - - - - + + + - + - + + + - - +
- - - - + + - + + - + - - + + + - - - -
- + - + + - + - + - - + + + - + + - + +
- + - + - - + + + + + + - + + - - - - -
- + + + + + - - + - - - - + - + - - + -
- + + - + + + + - + + + + - + - + - - -
+ - + + - - + - - - - - - + + - - - + -
+ - - + - + - + + - - + + + - + - - + -
- + - + - + - + - + + - + - + - + + - -
+ + - - - - - + - - - - + - + + + + + -
+ + - + - + + + + - + + + - + - + - + -
- + - - + - - - + + + - - - + + - + - +
- + - - - - + - - + - + + - - - + - - +
+ - + - + + + + - - + - + - - - + - + +
+ - - - - - + - - - - + - - - + - + - +
+ + - + - + + + - - + + + + + - - - - -
B - - - + - + - - + + - - + + + + - + +
輸出45