您的位置:首页 > 大数据 > 人工智能

Sailing(BFS 金马五校赛-东华大学 )

2017-07-18 11:23 274 查看

Problem B : Sailing

From:
DHUOJ, 2017060302

<a type="button" class="btn btn-default" href="/solution/submit.html?problemId=5285">Submit</a> (Out of Contest)

Time Limit: 1 s

Description

Handoku is sailing on a lake at the North Pole. The lake can be considered as a two-dimensional square plane containing
N × N blocks, which is shown in the form of string containing '*' and '#' on the map.

* : a normal block;
# : a block containing pack ice.



Handoku is at (1, 1) initially, and his destination is (N, N). He can only move to one of the four adjacent blocks. Sailing around pack ice is dangerous and stressful, so he needs power to remain vigilant. That means if he moves from a '*'
block to a '#' block or moves from a '#' block to any another block, he needs to consume 1 unit power. In other cases, he can enjoy the scene on his boat without consuming any power.

Now Handoku wants to know how many units power will be consumed at least during his sailing on the lake.

 

Input

There are several test cases (no more than 20).

For each test case, the first line contains a single integer N (3 ≤
N ≤ 50), denoting the size of the lake. For the following N lines, each line contains a
N-length string consisting of '*' and '#', denoting the map of the lake.

 

Output

For each test case, output exactly one line containing an integer denoting the answer of the question above.

 

Sample Input

3
**#
**#
*#*
3
##*
#*#
###
4
**##
#**#
##**
###*

 

Sample Output

2
4
0

 

Author: handoku

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <queue>
using namespace std;
const int maxn = 110;
const int inf = 0x3f3f3f3f;
char save[maxn][maxn];
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int n,d[maxn][maxn];
int bfs(){
queue<pair<int,int> > que;
int i,j;
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
d[i][j] = inf;
}
}
que.push(make_pair(1,1));
d[1][1] = 0;
while(!que.empty()){
pair<int,int> q = que.front();
que.pop();
for(i=0;i<4;i++){
int nx = q.first + dx[i];
int ny = q.second + dy[i];
int a = d[q.first][q.second]+1;
int c = d[q.first][q.second];
if(nx>=1&&nx<=n&&ny>=1&&ny<=n&&(d[nx][ny]>a||d[nx][ny]>c)){
if(save[q.first][q.second]=='*'&&save[nx][ny]=='#'){
d[nx][ny] = d[q.first][q.second]+1;
que.push(make_pair(nx,ny));
}else if(save[q.first][q.second]=='#'){
d[nx][ny] = d[q.first][q.second]+1;
que.push(make_pair(nx,ny));
}else if(save[q.first][q.second]=='*'&&save[nx][ny]=='*'){
d[nx][ny] = d[q.first][q.second];
que.push(make_pair(nx,ny));
}
}
}
}
return d

;
}
int main() {
int i,j;
char in[maxn];
while(~scanf("%d",&n)){
getchar();
for(i=1;i<=n;i++){
scanf("%s",in);
for(j=1;j<=n;j++){
save[i][j] = in[j-1];
}
}
int res = bfs();
printf("%d\n",res);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: