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

2017年上海金马五校程序设计竞赛:Problem B : Sailing

2017-06-04 20:49 603 查看


Problem B : Sailing

From: DHUOJ, 2017060302

Submit (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


题目意思就是从左上角开始,如果走“*”就不消耗时间,走“#”则消耗1的时间,从“#”走到任意地点都要消耗1的时间。问走到右下角所需要的最短时间。(1),(1)->(n),(n)的最短。时间

首先想到的就是优先队列,直接求最短的时间就可以了,。

代码借鉴dalao的   0.0  ~_~

#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int n;
char Map[55][55];
int vis[55][55];
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
struct node
{
int x;
int y;
int step;
friend bool operator<(node a,node b)
{
return a.step>b.step;
}
};
int BFS(int x,int y,int k)
{
priority_queue<node> Q;
node q,p;
p.x=x;
p.y=y;
p.step=0;
Q.push(p);
while(!Q.empty())
{
q=Q.top();
if(q.x==n&&q.y==n)
{
return q.step;
}
Q.pop();
for(int i=0;i<4;i++)
{
int xx=q.x+dir[i][0];
int yy=q.y+dir[i][1];
if(xx>=1&&xx<=n&&yy>=1&&yy<=n)
{
if(Map[q.x][q.y]=='*')
{
if(Map[xx][yy]=='#')
p.step=q.step+1;
else
p.step=q.step;
}
else
p.step=q.step+1;
p.x=xx;
p.y=yy;
if(vis[xx][yy]>p.step)
{
vis[xx][yy]=p.step;
Q.push(p);

}
}
}
}
return 0;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(vis,0x3f3f3f,sizeof(vis));
for(int i=1;i<=n;i++)
{
getchar();
for(int j=1;j<=n;j++)
scanf("%c",&Map[i][j]);
}
vis[1][1]=1;
cout<<BFS(1,1,0)<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  搜索
相关文章推荐