洛谷 P1649 [USACO07OCT]障碍路线Obstacle Course

Posted 一蓑烟雨任生平

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了洛谷 P1649 [USACO07OCT]障碍路线Obstacle Course相关的知识,希望对你有一定的参考价值。

题目描述

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[101][101];
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
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=0;i<4;i++){
        int cx=x+dx[i];
        int cy=y+dy[i];
        if(cx>=1&&cx<=n&&cy>=1&&cy<=n&&!map[cx][cy]){
            map[cx][cy]=1;
            if(i!=pre&&pre!=4)    dfs(cx,cy,tot+1,i);
            else dfs(cx,cy,tot,i);
            map[cx][cy]=0;
        }
    }
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++) {
            char x;cin>>x;
            if(x==x)    map[i][j]=1;
            else map[i][j]=0;
            if(x==A){ sx=i;sy=j; }
            else if(x==B){ tx=i;ty=j; }
        }
    }
    dfs(sx,sy,0,4);
    if(ans!=2139062143)    cout<<ans;
    else cout<<"-1";
}
/*
5
. . B x .
. x x A .
. . . x .
. x . . .
. . x . .
*/

 

以上是关于洛谷 P1649 [USACO07OCT]障碍路线Obstacle Course的主要内容,如果未能解决你的问题,请参考以下文章

bzoj1644 / P1649 [USACO07OCT]障碍路线Obstacle Course

[USACO07OCT]障碍路线Obstacle Course

[USACO07OCT]障碍路线 & yzoj P1130 拐弯 题解

洛谷—— P1339 [USACO09OCT]热浪Heat Wave

洛谷——P2958 [USACO09OCT]木瓜的丛林Papaya Jungle

洛谷——P1596 [USACO10OCT]湖计数Lake Counting