胖胖的牛牛(dfs)

在這裏插入圖片描述

思路:記錄一下他的上一次所走的方向,只有從前後方向變成左右方向步數纔會加或者左右方向變成前後

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e4+7;
const int N=2e5+10;
const int inf=0x7f7f7f7f;


ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
    return a*(b/gcd(a,b));
}

template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
        write(x / 10);
    putchar('0' + x % 10);
}
struct node
{
    int x,y,step,now;
};
int n;
int vis[200][200];
char mp[200][200];
int ans;
queue<node> q;
int dir[4][2]{{1,0},{0,1},{0,-1},{-1,0}};

void dfs(int x,int y,int sum,int pre)
{
    if(mp[x][y]=='B')
    {
        ans=min(ans,sum);
    }
    if(sum>=ans)return ;
    for(int i=0;i<4;i++)
    {
        int xx=x+dir[i][0];
        int yy=y+dir[i][1];
        if(xx<=n&&xx>=1&&yy>=1&&yy<=n&&mp[xx][yy]!='x'&&!vis[xx][yy])
        {
            if(pre==-1)
            {
                vis[xx][yy]=1;
                dfs(xx,yy,sum,i);
                vis[xx][yy]=0;
            }
            else if(pre!=i&& pre+i!=3)//前後變左右或者左右邊變成後
            {
                vis[xx][yy]=1;
                dfs(xx,yy,sum+1,i);
                vis[xx][yy]=0;
            }
            else
            {
                vis[xx][yy]=1;
                dfs(xx,yy,sum,i);
                vis[xx][yy]=0;
            }
        }
    }


}
int main()
{
    SIS;
    ans=inf;
    cin>>n;
    int sx,sy;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
             cin>>mp[i][j];
             if(mp[i][j]=='A')
             {
                 sx=i,sy=j;
                 vis[i][j]=1;
             }

        }

    }
    dfs(sx,sy,0,-1);
    if(ans==inf)
        cout<<-1;
    else
        cout<<ans;


    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章