Find a way --搜索

本文介绍了一个算法问题,旨在找到两个朋友从不同起点出发,在宁波地图上寻找距离最近的肯德基会面的最短总时间。通过两次搜索,分别计算从各自位置到所有肯德基点的距离,最终确定最小总行走时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

思路:@代表肯德基,Y,M要在@见面,要进同一家肯德基店,并且走的步数要最短。

搜索两次:

        第一次搜索Y到@的距离;

        第二次搜索M到@的距离;

        求最短的距离即可;

代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
int n,m;
int time[1000][1000];
struct node
{
    int x;
    int y;
    int step;
};
char mp[1000][1000];
int dx[]={1,0,0,-1};
int dy[]={0,1,-1,0};
int flag[1000][1000];
void bfs(int sx,int sy)
{
    memset(flag,0,sizeof(flag));
    queue<node>q;
    q.push(node{sx,sy});
    node tmp;
    while(!q.empty())
    {
        node top=q.front();
        q.pop();
        if(mp[top.x][top.y]=='@')
            time[top.x][top.y]+=top.step;
        for(int i=0;i<4;i++)
        {
            tmp.x=top.x+dx[i];
            tmp.y=top.y+dy[i];
            tmp.step=top.step+1;
            if(tmp.x>=0&&tmp.x<n&&tmp.y>=0&&tmp.y<m&&mp[tmp.x][tmp.y]!='#'&&flag[tmp.x][tmp.y]==0)
             {//是否满足条件
                 flag[tmp.x][tmp.y]=1;//标记
                 q.push(tmp);
             }

        }
    }
}
int main()
{
    int mx,my;
    int yx,yy;
    while(cin>>n>>m)
    {
        int ans=INT_MAX;
        memset(time,0,sizeof(time));
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                cin>>mp[i][j];
            }
        }
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(mp[i][j]=='Y')
                {
                    yx=i;
                    yy=j;
                }
                if(mp[i][j]=='M')
                {
                    mx=i;
                    my=j;
                }
            }
        }
         bfs(mx,my);
         bfs(yx,yy);

        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(time[i][j])
                    ans=min(time[i][j],ans);
            }
        }
        cout<<ans*11<<endl;
    }
    return 0;
}

 

### L2-010 排座位 测试点二 解决方案 对于L2-010排座位问题中的测试点二未通过的情况,通常是因为算法未能正确处理某些特殊情况下的关系判定逻辑。以下是可能的原因分析以及解决方案。 #### 可能原因 1. **图的连通性判断错误** 如果两个宾客既不是朋友也不是敌人,但在同一连通分量中存在其他间接的朋友或敌对关系,则可能导致误判[^2]。 2. **敌对与友好的冲突检测不足** 当两人之间既有友好又有敌对的关系链路时,需特别注意是否有共同的朋友连接这两者。如果没有正确实现这一逻辑,可能会导致输出不匹配预期结果[^3]。 3. **边界条件遗漏** 特殊情况如孤立节点(无任何关系)、自环(自己对自己定义关系)或者重复边等问题也可能影响最终的结果准确性。 #### 改进建议及代码示例 为了更精确地解决这些问题,可以采用深度优先搜索(DFS)来遍历整个图结构并记录各个节点间的关系状态。具体改进措施如下: - 使用邻接表存储所有的关系信息; - 对于每次查询操作执行两次独立的 DFS 遍历来分别寻找是否存在路径使得两者成为朋友(-1标记)或是敌人(+1标记); - 增加额外标志位用于区分当前访问过程中遇到的是哪种类型的关系; - 考虑到可能存在多个解法满足题目要求, 应该选取最保守的那个作为答案. 下面是基于 Python 的参考实现: ```python from collections import defaultdict def dfs(u, target, relation_graph, visited, sign): """Depth First Search function to find relationship.""" if u == target: return True result = False for v in relation_graph[u]: if not visited[v]: visited[v] = True current_sign = relation_graph[u][v] if current_sign * sign >= 0 and dfs(v, target, relation_graph, visited, current_sign * sign): return True return result n, m, k = map(int, input().split()) relation_graph = defaultdict(dict) for _ in range(m): a, b, r = map(int, input().split()) relation_graph[a][b] = r relation_graph[b][a] = r queries = [] for _ in range(k): queries.append(tuple(map(int, input().split()))) results = [] for query in queries: start, end = query visited_friend = {i:False for i in range(1,n+1)} visited_enemy = {i:False for i in range(1,n+1)} is_friend = dfs(start, end, relation_graph, visited_friend.copy(), 1) is_enemy = dfs(start, end, relation_graph, visited_enemy.copy(), -1) if is_friend and not is_enemy: results.append("No problem") elif not is_friend and not is_enemy: results.append("OK") elif is_friend and is_enemy: results.append("OK but...") else: results.append("No way") print("\n".join(results)) ``` 此代码片段实现了上述提到的功能需求,并且能够有效应对各种复杂场景下的输入数据集。 ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值