[洛谷] P2802 回家

 

dfs 标记 + 回溯

//#pragma GCC optimize(2)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;

const int MAXN = 1e2 + 10;

int n, m, bx, by;

int movel[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

int arr[MAXN][MAXN], ans = 0x3f3f3f3f;

int used[MAXN][MAXN];

void dfs(int x, int y, int hp, int step)
{
    if(hp == 0 || arr[x][y] == 0 || used[x][y] == 1)
        return ;

    if(!(x >= 0 && x <= n && y >= 0 && y <= m))
        return ;

    if(arr[x][y] == 3)
    {
        ans = min(ans, step);
        return ;
    }

    if(arr[x][y] == 4)
        hp = 6;
    
    used[x][y] = 1;
    for(int i = 0; i < 4; i++)
    {

        dfs(x + movel[i][0], y + movel[i][1], hp - 1, step + 1);
    }
    used[x][y] = 0;
}

int main()
{
    //ios::sync_with_stdio(false);

    //cin.tie(0);     cout.tie(0);

    cin>>n>>m;

    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
        {
            cin>>arr[i][j];
            if(arr[i][j] == 2)
                bx = i, by = j;
        }
    
    dfs(bx, by, 6, 0);

    ans >= 0x3f3f3f3f ? cout<<"-1"<<endl : cout<<ans<<endl;

    return 0;
}

 

posted @ 2018-09-24 18:31  张浦  阅读(140)  评论(0编辑  收藏  举报