题目描述

Consider an N x N (1 <= N <= 100) square field composed of 1

by 1 tiles. Some of these tiles are impassible by cows and are marked with an 'x' in this 5 by 5 field that is challenging to navigate:

. . B x .
. x x A .
. . . x .
. x . . .
. . x . .

Bessie finds herself in one such field at location A and wants to move to location B in order to lick the salt block there. Slow, lumbering creatures like cows do not like to turn and, of course, may only move parallel to the edges of the square field. For a given field, determine the minimum number of ninety degree turns in any path from A to B. The path may begin and end with Bessie facing in any direction. Bessie knows she can get to the salt lick.

N*N(1<=N<=100)方格中,’x’表示不能行走的格子,’.’表示可以行走的格子。卡门很胖,故而不好转弯。现在要从A点走到B点,请问最少要转90度弯几次?

输入输出格式

输入格式:

第一行一个整数N,下面N行,每行N个字符,只出现字符:’.’,’x’,’A’,’B’,表示上面所说的矩阵格子,每个字符后有一个空格。

【数据规模】

2<=N<=100

输出格式:

一个整数:最少转弯次数。如果不能到达,输出-1。

输入输出样例

输入样例#1: 复制

3
. x A
. . .
B x .
输出样例#1: 复制

2

说明

【注释】

只可以上下左右四个方向行走,并且不能走出这些格子之外。开始和结束时的方向可以任意。

思路:搜索。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int map[][];
int dx[]={,-,,};
int dy[]={,,,-};
int n,sx,sy,tx,ty,ans=0x7f7f7f7f;
void dfs(int x,int y,int tot,int pre){
if(tot>ans) return ;
if(x==tx&&y==ty&&tot<ans){
ans=tot;
return ;
}
for(int i=;i<;i++){
int cx=x+dx[i];
int cy=y+dy[i];
if(cx>=&&cx<=n&&cy>=&&cy<=n&&!map[cx][cy]){
map[cx][cy]=;
if(i!=pre&&pre!=) dfs(cx,cy,tot+,i);
else dfs(cx,cy,tot,i);
map[cx][cy]=;
}
}
}
int main(){
scanf("%d",&n);
for(int i=;i<=n;i++){
for(int j=;j<=n;j++) {
char x;cin>>x;
if(x=='x') map[i][j]=;
else map[i][j]=;
if(x=='A'){ sx=i;sy=j; }
else if(x=='B'){ tx=i;ty=j; }
}
}
dfs(sx,sy,,);
if(ans!=) cout<<ans;
else cout<<"-1";
}
/*
5
. . B x .
. x x A .
. . . x .
. x . . .
. . x . .
*/

最新文章

  1. Python traceback【转】
  2. ionic 踩过的坑
  3. 用webdriver+phantomjs实现无浏览器的自动化过程
  4. Codeforces Beta Round #80 (Div. 2 Only)【ABCD】
  5. PostgreSQL Replication之第九章 与pgpool一起工作(6)
  6. 2.3CUDA矩阵乘法
  7. Ubuntu14 或是其他系统当中关于sublimeSFTP超时解决方法
  8. 定位--position属性
  9. 201621123088《Java程序设计》第1周学习总结
  10. Java基础系列--集合之ArrayList
  11. hdu 5830 FFT + cdq分治
  12. php序列化漏洞理解
  13. intent flags标记
  14. Ehcache 3.7文档—基础篇—XML Configuration
  15. react-redux中的数据传递
  16. poj 3279 Fliptile(二进制搜索)
  17. Power BI中DAX的动态计算方差
  18. 打印小票,使用的是BarcodeLib
  19. SDL示例一:实现七段数码管的显示
  20. 最全的select加锁分析(Mysql)

热门文章

  1. C++&lt;iomanip&gt;控制符
  2. 【POJ 1964】 City Game
  3. SiteMesh3使用实例和详解
  4. ThinkPHP __PUBLIC__的定义 __ROOT__等 常用 常量的定义
  5. Nmap linux端口扫描神器
  6. js基础---数组方法
  7. 基于CXF搭建webService
  8. Android Studio Library 编译成 jar,aar
  9. Java数据的基本类型
  10. js 事件冒泡、事件捕获、stopPropagation、preventDefault