Problem B : Sailing
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[n][n];
}
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;
}