1. 程式人生 > >ECNU 3260 袋鼠媽媽找孩子(dfs)

ECNU 3260 袋鼠媽媽找孩子(dfs)

highlight 另一個 () class div names 中一 ble problem

鏈接:http://acm.ecnu.edu.cn/problem/3260/

題意:

給出一個x,y,k。求從左上角到(x,y)最短路徑不少於k而且最快到達(x,y)的迷宮。(迷宮有多個 輸出其中一個就行)

分析:

因為數據量很少,而且限時很寬,可以考慮dfs。限制是每個要走的格四個方向只能有一個走過的格,其實就是上一個走到這個格子的格,因為如果有多於一個相鄰的格子,那麽就會從另一個格子走到這格而不是從另一個格子走到上一個格子再走到這格,所以限制條件是成立的。

#include <bits/stdc++.h>
using namespace std;
int G[10][10];
int n,m,fx,fy,k ,maxx = 9999;
int dir[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int ans[10][10];
void dfs(int x,int y,int step)
{

    int cnt = 0,tx, ty;
    for(int i = 0; i < 4; i++)
    {
        tx = x, ty = y;
        tx += dir[i][0];
        ty += dir[i][1];
        if(tx < 1 || tx >n || ty<1 || ty > m)
            continue;
        if(G[tx][ty]) cnt++;
    }
    if(cnt > 1) return;

    if(x == fx && y == fy && step >= k)
    {
        if(step < maxx)
        {
//            printf("%d\n", step);
            maxx = step;
            for(int i = 1; i <= n; i++)
            {
                for(int j = 1; j <= m; j++)
                {
                    if(G[i][j]) ans[i][j] = ‘.‘;
                    else ans[i][j] = ‘*‘;
                }
            }
        }
        else return;
    }

    for(int i = 0; i < 4; i++)
    {
        tx = x, ty = y;
        tx += dir[i][0];
        ty += dir[i][1];
        if(tx < 1 || tx >n || ty<1 || ty > m || G[tx][ty])
            continue;
        G[tx][ty] = 1;
        dfs(tx,ty,step+1);
        G[tx][ty] = 0;
    }
}
int main()
{
    memset(G,0,sizeof(G));
    scanf("%d %d", &n, &m);
    scanf("%d %d %d", &fx, &fy, &k);
    G[1][1] = 1;
    dfs(1,1,0);
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++)
        {
            printf("%c",ans[i][j]);
        }
        printf("\n");
    }
}

  

ECNU 3260 袋鼠媽媽找孩子(dfs)