Find a way hdu2612

本文介绍了一道算法题目,通过广度优先搜索(BFS)来找出两个人从不同起点出发到达同一目的地(KFC)的最短总时间。文章提供了完整的代码实现,并解释了解题思路。

Find a way

Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 3   Accepted Submission(s) : 3
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.
Input
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’    express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
Output
For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.
Sample Input

4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#

Sample Output

66
88
66

AC代码:
#include<stdio.h>
#include<memory.h>
int step[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
char map[201][201];
int z[201][201],v[201][201],Y_x,Y_y,M_x,M_y,n,m;
struct none
{
    int x,y;
    int count;
}q[40001];
void BFS(int x,int y)
{
    int i;
    int fornt,end,tempx,tempy,count;
    memset(z,0,sizeof(z));
    fornt=1;end=1;
    q[end].x=x;
    q[end].y=y;
    q[end].count=0;
    end++;
    while(fornt!=end)
    {
        for(i=0;i<4;i++)
        {
            tempx=q[fornt].x+step[i][0];
            tempy=q[fornt].y+step[i][1];
            if(tempx>=0&&tempx<n&&tempy>=0&&tempy<m)
            {
                if(map[tempx][tempy]!='#'&&z[tempx][tempy]==0)
                {
                    q[end].x=tempx;
                    q[end].y=tempy;
                    q[end].count=q[fornt].count+1;
                    end++;
                    z[tempx][tempy]=1;
                    if(map[tempx][tempy]=='@')
                    {
                        v[tempx][tempy]+=q[end-1].count;
                    }
                }
            }
        }
        fornt++;
    }
}
int main()
{
    freopen("IO.txt","r",stdin);
    int i,j,min;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(i=0;i<n;i++)
            scanf("%s",map[i]);
        for(i=0;i<n;i++)
            for(j=0;j<m;j++)
            {
                if(map[i][j]=='Y')
                {
                    Y_x=i;
                    Y_y=j;
                }
                if(map[i][j]=='M')
                {
                    M_x=i;
                    M_y=j;
                }
            }
        min=999999999;
        memset(v,0,sizeof(v));
        BFS(Y_x,Y_y);
        BFS(M_x,M_y);
        for(i=0;i<n;i++)
            for(j=0;j<m;j++)
            {
                if(min>v[i][j]&&v[i][j]!=0)
                    min=v[i][j];
            }
        printf("%d/n",min*11);
    }
    return 0;
}

解题思路:
此题要用求出最短的路程,可以用广搜,因为有多个KFC,所以难以知道怎么才是最短的,可以先把Y去每个KFC的路程求出,存在V数组中,然后把M去每个KFC的路程求出,加到V数组中,这样只要遍历V就可以得出最短的路径了,两次广搜加遍历

### HDU 1682 Problem Explanation and Solution HDU 1682 is titled "Find a way". This problem involves finding the shortest path in a grid with specific constraints. The grid contains obstacles, and the task is to determine the minimum number of steps required to reach the destination from the starting point while avoiding obstacles[^5]. #### Problem Description The input consists of multiple test cases. Each test case includes: - A grid size `N x M`. - A grid where each cell is either empty (denoted by '.') or blocked (denoted by '#'). - The starting position `(x1, y1)` and the destination position `(x2, y2)`. The goal is to find the shortest path from the start to the destination, moving only up, down, left, or right, and avoiding blocked cells. #### Approach This problem can be solved using **Breadth-First Search (BFS)**, which is ideal for finding the shortest path in an unweighted graph. BFS ensures that the first time a node is visited, it is reached via the shortest possible path from the source. Here is a step-by-step explanation of the algorithm: - Represent the grid as a 2D array. - Use a queue to store the current position and the number of steps taken to reach it. - Mark visited cells to avoid revisiting them. - Expand the search in all four directions (up, down, left, right) at each step. - If the destination is reached, output the number of steps. Otherwise, if no path exists, output -1. #### Implementation Below is a Python implementation of the solution: ```python from collections import deque def solve(): T = int(input()) # Number of test cases results = [] for _ in range(T): N, M = map(int, input().split()) # Grid dimensions grid = [input().strip() for _ in range(N)] x1, y1, x2, y2 = map(int, input().split()) # Start and end positions # Adjust for zero-based indexing x1 -= 1; y1 -= 1; x2 -= 1; y2 -= 1 # BFS Initialization queue = deque([(x1, y1, 0)]) # (current_x, current_y, steps) visited = [[False] * M for _ in range(N)] visited[x1][y1] = True # Directions: up, down, left, right directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] found = False while queue: cx, cy, steps = queue.popleft() if cx == x2 and cy == y2: results.append(steps) found = True break for dx, dy in directions: nx, ny = cx + dx, cy + dy if 0 <= nx < N and 0 <= ny < M and not visited[nx][ny] and grid[nx][ny] == '.': visited[nx][ny] = True queue.append((nx, ny, steps + 1)) if not found: results.append(-1) for result in results: print(result) # Example Input/Output # Input: # 1 # 3 3 # ... # .## # ... # 1 1 3 3 # Output: # 4 ``` #### Key Points - BFS guarantees the shortest path in an unweighted grid. - Visited cells are marked to prevent cycles and redundant computations. - The algorithm terminates early if the destination is reached.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值