Shortest path of the king(比赛2.A)

本文探讨了在棋盘上,国王从一个位置移动到另一个特定位置的最短路径问题,详细介绍了使用广度优先搜索(BFS)解决该问题的方法,并提供了正确的代码实现。

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

1.题目:

Home	Problems	Status	Contest	[acgirl]	Logout
NEFU要崛起——第2场
3:00:00
OverviewProblemStatusRankDiscuss

A
 
B
 
C
 
D
A - Shortest path of the king
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit
 
Status
 
Practice
 
CodeForces 3A
Description
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least number of moves. Help him to do this.


In one move the king can get to the square that has a common side or a common vertex with the square the king is currently in (generally there are 8 different squares he can move to).

Input
The first line contains the chessboard coordinates of square s, the second line — of square t.

Chessboard coordinates consist of two characters, the first one is a lowercase Latin letter (from a to h), the second one is a digit from 1 to 8.

Output
In the first line print n — minimum number of the king's moves. Then in n lines print the moves themselves. Each move is described with one of the 8: L, R, U, D, LU, LD, RU or RD.

L, R, U, D stand respectively for moves left, right, up and down (according to the picture), and 2-letter combinations stand for diagonal moves. If the answer is not unique, print any of them.

Sample Input
Input
a8
h1
Output
7
RD
RD
RD
RD
RD
RD
RD
FAQ | About Virtual Judge | Forum | Discuss | Open Source Project
All Copyright Reserved ©2010-2012 HUST ACM/ICPC TEAM 
Anything about the OJ, please ask in the forum, or contact author:Isun
Server Time: 


 

2.题意:已知起点,终点,可以上、下、左、右、左上、左下、右上、右下8个方向走。输出最短路径及每步走的方向

3.思路:bfs

4.一直wrong,待改正

wrong代码:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<iostream>
using namespace std;
int sx,sy,ex,ey;
int path[100];
int dir[8][2]={1,1,1,-1,-1,-1,-1,1,0,-1,1,0,-1,0,0,1};
struct node
{
    int x;
    int y;
    int px,py;
    int step;
    int d;
    int visit;
}a[10][10];
int bfs(int n)
{
    memset(a,0,sizeof(a));
    queue<node> q;
    node cur;
    a[sx][sy].x=sx;
    a[sx][sy].y=sy;
    a[sx][sy].step=0;
    a[sx][sy].visit=1;
    q.push(a[sx][sy]);
    int aa=1<<29;
    while(!q.empty())
    {
        cur=q.front();//赋值
        q.pop();
        if(cur.x==ex&&cur.y==ey)
        {
            //printf("cur=%d\n",cur.step);
           aa=cur.step;
            break;
        }
        for(int i=0;i<8;i++)
        {
            int tx=cur.x+dir[i][0];
            int ty=cur.y+dir[i][1];
            if(tx>0&&tx<=n&&ty>0&&ty<=n&&a[tx][ty].visit==0)
            {
                a[tx][ty].visit=1;
                a[tx][ty].px=cur.x;
                a[tx][ty].py=cur.y;
                a[tx][ty].x=tx;
                a[tx][ty].y=ty;
                a[tx][ty].step=cur.step+1;
                a[tx][ty].d=i;
                q.push(a[tx][ty]);
            }
        }
    }
    return  aa;
}
int main()
{
    char s,e;
    int n=8;
    scanf("%c%d",&s,&sy);
    getchar();
    sx=(s-'a')+1;
    scanf("%c%d",&e,&ey);
    getchar();
    ex=(e-'a')+1;
    int w=bfs(n);
    printf("%d\n",w);
    if(w==0)
    return 0;
    int tx=a[ex][ey].px,ty=a[ex][ey].py;
    int i=0;
    path[i++]=a[ex][ey].d;
    while(tx!=sx&&ty!=sy)
    {
        path[i++]=a[tx][ty].d;
        tx=a[tx][ty].px;
        ty=a[tx][ty].py;
    }
    for(int j=i-1;j>=0;j--)
    {
        switch(path[j])
        {
            case 0:
            printf("RU\n");
            break;
            case 1:
            printf("RD\n");
            break;
            case 2:
            printf("LD\n");
            break;
            case 3:
            printf("LU\n");
            break;
            case 4:
            printf("D\n");
            break;
            case 5:
            printf("R\n");
            break;
            case 6:
            printf("L\n");
            break;
            case 7:
            printf("RU\n");
            break;
        }
    }
    return 0;
}


 

4.accept代码:

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int move[8][2]={{0,-1},{0,1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};
//             左 L    右  R 下  D  上 U    右下 RD  左下  LD  右上RU    左上LU
char mo[8][3]={'L','R','D','U','RD','LD','RU','LU'};
int ex,ey,sx,sy;
struct node{
    int x,y;
    int vis;
    int depth;
    int shx,shy;
    int m;
}pan[10][10];
int bfs()
{
    int i,j,k;
    queue<node> q;
    q.push(pan[sx][sy]);
    if(sx==ex&&sy==ey)
    return 0;
    pan[sx][sy].vis=1;
    while(!q.empty())
    {
        node p;
        int tx,ty,yx,yy;
        p=q.front();
        q.pop();

            for(i=0;i<8;i++)
            {
				node t;
				t=p;
                tx=p.x+move[i][0];
                ty=p.y+move[i][1];
                if(tx<0||tx>=8||ty<0||ty>=8)
                    continue;
                if(pan[tx][ty].vis==0)
                {
                    pan[tx][ty].shx=p.x;
					pan[tx][ty].shy=p.y;
                    pan[tx][ty].depth=p.depth+1;
                    q.push(pan[tx][ty]);
                    pan[tx][ty].vis=1;
                    pan[tx][ty].m=i;

                    if(tx==ex&&ty==ey)
                        return pan[tx][ty].depth;
                }
            }


    }
    return 0;
}
void init()
{
    int i,j;
    for(i=0;i<8;i++)
    {
        for(j=0;j<8;j++)
        {
            pan[i][j].x=i;
            pan[i][j].y=j;
        }
    }
}
int main()
{
    int i,j,k,l,m,n;
    memset(pan,0,sizeof(pan));
    init();
    char z,v;
    scanf("%c%c",&z,&v);//先y(字母)后x
    sy=z-'a';
	sx=8-v+48;
	getchar();
    scanf("%c%c",&z,&v);
    ey=z-'a';
	ex=8-v+48;
	m=bfs();
    printf("%d\n",m);
    if(m==0)
    return 0;
    int  path[100];
    memset(path,0,sizeof(path));
    j=0;
    path[j++]=pan[ex][ey].m;
	int qx,qy;
	qx=pan[ex][ey].shx;
	qy=pan[ex][ey].shy;
    while(qx!=sx||qy!=sy)
    {
		int tx,ty;
		tx=qx;ty=qy;
		qx=pan[tx][ty].shx;
		qy=pan[tx][ty].shy;
        path[j++]=pan[tx][ty].m;
        //printf("%d\n",p->m);
    }
    for(i=j-1;i>=0;i--)
	{
		int k=path[i];
		if(k==0)
		printf("L\n");
		else if(k==1)
		printf("R\n");
		else if(k==2)
		printf("D\n");
		else if(k==3)
		printf("U\n");
		else if(k==4)
		printf("RD\n");
		else if(k==5)
		printf("LD\n");
		else if(k==6)
		printf("RU\n");
		else if(k==7)
		printf("LU\n");
	}

return 0;
}


 

<think>好的,我需要帮用户在他们的网络分析代码中添加最短路径分析的部分。用户之前已经添加了网络密度计算,现在需要进一步计算平均最短路径长度以及特定角色之间的最短路径,比如Jean Valjean和Cosette。 首先,我得确认用户使用的是NetworkX库,因为之前的代码用了nx.density。所以,继续用NetworkX的函数来实现最短路径分析是合理的。 平均最短路径长度可以用nx.average_shortest_path_length函数,但需要注意这个函数只适用于连通图。如果图不连通,会抛出错误。因此,在代码中需要先检查图是否连通。如果不连通,可能需要计算每个连通子图的平均路径,或者使用其他方法处理。不过用户可能希望得到整个网络的平均,即使不连通,这时候可能需要使用其他方式,比如忽略无穷大的路径或者取各连通分量的平均值。但根据NetworkX文档,这个函数在不连通的图上会报错,所以需要先处理。 用户可能没有考虑到图是否连通的问题,所以需要在代码中添加连通性检查,并给出相应的处理。比如,如果图不连通,则输出提示,并计算每个连通分量的平均最短路径长度,或者使用其他指标。但用户的需求是计算整个网络的平均,可能需要先确保图是连通的,或者调整代码处理不连通的情况。 接下来,查找两个特定节点之间的最短路径,使用nx.shortest_path函数。需要确保这两个节点存在于图中,否则会出错。因此,在代码中需要添加异常处理,比如try-except块,来捕获节点不存在的错误,并给出友好的提示。 现在,用户提供的示例代码中没有提到节点是如何命名的,但假设节点名称是字符串,比如"Jean Valjean"和"Cosette"。需要确保代码中正确引用这些节点名称,可能需要用户事先确认节点名称的正确性,或者处理大小写、空格等问题。 另外,输出结果时需要明确,比如平均最短路径长度是多少,特定节点之间的路径是什么。同时,需要解释结果的意义,比如平均路径小表示网络紧密,大则表示节点间需要较多步骤连接。 在代码结构方面,用户之前将网络分析模块分为3.1到3.4,现在新增的最短路径分析可以作为3.5。需要将代码插入到合适的位置,比如在PageRank计算之后,网络密度分析之前或之后,根据逻辑顺序安排。 技术解析部分需要解释平均最短路径的计算方法,比如使用BFS或Dijkstra算法(如果图是加权的),但用户的问题中没有提到权重,所以默认是无权图,使用BFS。同时,解释“六度分隔理论”等概念,帮助用户理解结果的意义。 示例输出部分需要展示可能的运行结果,比如平均路径长度和具体路径,以及当节点不存在时的提示信息。 最后,扩展分析建议可以包括可视化最短路径,或者与其他指标结合分析,比如中心性高的节点是否在关键路径上。用户可能需要进一步的指导,所以提供这些建议是有帮助的。 总结步骤: 1. 添加平均最短路径计算,处理图的连通性问题。 2. 添加特定节点间最短路径查找,处理节点不存在的情况。 3. 将代码整合到现有结构中,保持结构清晰。 4. 添加结果解释,帮助用户理解数值意义。 5. 提供异常处理和友好提示,增强代码健壮性。</think>--- ### **新增代码实现**(在网络分析模块中继续添加) ```python # ------------------------------ # 3.5 最短路径分析(新增模块) # ------------------------------ # 核心计算语句 try: avg_shortest_path = nx.average_shortest_path_length(G) print("\n===== 最短路径分析 =====") print(f"网络平均最短路径长度: {avg_shortest_path:.2f}") except nx.NetworkXError: # 处理非连通图情况 print("警告:网络不连通,平均路径长度仅计算最大连通子图") largest_cc = max(nx.connected_components(G), key=len) subgraph = G.subgraph(largest_cc) avg_shortest_path = nx.average_shortest_path_length(subgraph) print(f"最大连通子图平均路径长度: {avg_shortest_path:.2f}") # 指定角色间最短路径 node_a = "Jean Valjean" # 可修改为实际节点名 node_b = "Cosette" # 可修改为实际节点名 try: shortest_path = nx.shortest_path(G, node_a, node_b) print(f"\n[{node_a} ↔ {node_b}] 最短路径:") print(" → ".join(shortest_path)) print(f"路径长度: {len(shortest_path)-1}跳") except nx.NodeNotFound: print(f"\n错误:节点 {node_a} 或 {node_b} 不存在于图中") except nx.NetworkXNoPath: print(f"\n警告:{node_a} 与 {node_b} 之间无连通路径") ``` --- ### **完整代码位置建议** ```python # (有数据加载和图构建代码不变) # ------------------------------ # 3. 网络分析 # ------------------------------ # 3.1 聚类系数计算... # 3.2 中介中心性计算... # 3.3 PageRank计算... # 3.4 网络密度计算... # 3.5 新增的最短路径分析代码如上 # ------------------------------ # 4. 可视化(保持不变) ``` --- ### **技术解析** 1. **关键算法**: - 平均路径计算使用 **广度优先搜索(BFS)**,时间复杂度 $O(n(n+m))$($n$=节点数,$m$=边数) - 节点间路径查找采用 **双向BFS优化**,比传统BFS快约22. **结果解读**: - **平均路径长度**: - 值越小 → 网络越紧密(例:社交网络 ≈3-6) - 值越大 → 节点间需更多中介(例:互联网路由 ≈15) - **六度分隔理论**:多数社交网络平均路径约6 3. **典型应用场景**: - 识别 **信息传播关键路径** - 发现 **隐藏的间接关联**(如共享联系人但无直接联系) - 评估 **网络抗毁性**(长路径更易被断开) --- ### **示例输出** ``` ===== 最短路径分析 ===== 网络平均最短路径长度: 2.87 [Jean Valjean ↔ Cosette] 最短路径: Jean Valjean → Fantine → Cosette 路径长度: 2跳 ``` --- ### **扩展分析建议** 1. **路径可视化**: ```python # 绘制指定路径 pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, nodelist=shortest_path, node_color='r') nx.draw_networkx_edges(G, pos, edgelist=list(zip(shortest_path[:-1], shortest_path[1:])), edge_color='r', width=3) nx.draw_networkx_labels(G, pos, labels={n:n for n in shortest_path}, font_color='w') plt.show() ``` 2. **路径统计分析**: ```python # 计算所有节点对的最短路径长度分布 all_path_lengths = [] for source in G.nodes(): for target in G.nodes(): if source != target: try: all_path_lengths.append(nx.shortest_path_length(G, source, target)) except nx.NetworkXNoPath: pass plt.hist(all_path_lengths, bins=10) plt.title("最短路径长度分布") plt.xlabel("跳数"); plt.ylabel("频次") ``` --- 如需增加带权路径计算(如关系亲密度作为边权重),请提供数据格式要求!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值