题解:P12270 [蓝桥杯 2024 国 Python B] 马与象

· · 题解

题意解释

给你一副 n \times n 的棋盘,再给你马和象的坐标,问你最少几步两者能相遇,即马吃象或象吃马。\ 众所周知:马飞日,象飞田。

思路分析

一道简单的宽搜。\ 这里介绍一下我的思路:

一:预处理

这题表示的马和象的坐标很难受,至少我这么认为。 因为题中表示的坐标是按平面直角坐标系的方式表示的,而数组不是这样的,所以让我们转换一下。

参考代码如下:

swap(xa,ya),swap(xb,yb);//交换横纵坐标
xa=n-xa+1,ya++;
xb=n-xb+1,yb++;

二:地图设置

先设置一张地图,把地图中的位置设置成象走到此处的步数,无法走到则置成 -1。\ 以样例一为例,地图设置成这样:

-1 -1 -1 1  -1
-1 -1 -1 -1 -1
-1 0  -1 -1 -1
-1 -1 -1 -1 -1
-1 -1 -1 1  -1

为下面马的遍历做铺垫。\ 参考代码如下:

void bfs1()
{
    while(!q.empty())
    {
        node temp=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            int xx=temp.x+ex[i];
            int yy=temp.y+ey[i];
            if(xx<1||yy<1||xx>(n+1)||yy>(n+1)) continue;
            if(a[xx][yy]!=(-1)) continue;
            a[xx][yy]=temp.step+1;
            q.push(node{xx,yy,temp.step+1});
        }
    }
 } 

想测试一下可以加上输出代码:

for(int i=1;i<=n+1;i++)
{
    for(int j=1;j<=n+1;j++) printf("%-2d ",a[i][j]);//左对齐
    cout<<endl;
}

三:马的遍历

相信大家都做过马的遍历。\ 那么这里简单介绍一下。

注意最后答案是马走的步数加上对应坐标上象到此处需走的步数。

参考代码如下:

void bfs2()
{
    while(!q.empty())
    {
        node temp=q.front();
        q.pop();
        if(a[temp.x][temp.y]!=(-1))
            ans=min(ans,(temp.step+a[temp.x][temp.y]));
        for(int i=0;i<8;i++)
        {
            int xx=temp.x+dx[i];
            int yy=temp.y+dy[i];
            if(xx<1||yy<1||xx>(n+1)||yy>(n+1)) continue;
            if(vis[xx][yy]) continue;
            vis[xx][yy]=1;
            q.push(node{xx,yy,temp.step+1});
        }
    }
}

四:总结

通过两次广度优先搜索,利用了记忆化搜索的思想,将从终点出发能到达的节点信息记录下来,然后从起点出发搜索到这些节点,从而找到最短路径。

那么接下来看看完整代码。

代码实现

c++ 代码:

#include<bits/stdc++.h> 
using namespace std; 

struct node{ 
    int x,y,step; 
}; 

int n,xa,ya,xb,yb,ans=1e9,sum; 
int a[55][55]; 
bool vis[55][55]; 
int dx[10]={2,2,1,1,-1,-1,-2,-2}; 
int dy[10]={1,-1,2,-2,2,-2,1,-1}; 
int ex[4]={2,2,-2,-2}; 
int ey[4]={2,-2,2,-2};  
queue <node> q; 

// 从终点出发进行第一次广度优先搜索 
// 目的是标记从终点按照特定移动规则(ex 和 ey 定义的移动方式)能到达的节点,并记录到达这些节点所需的步数 
void bfs1() 
{ 
    // 当队列不为空时,继续搜索 
    while(!q.empty())  
    { 
        // 取出队列的队首元素 
        node temp=q.front();  
        q.pop();  
        // 遍历 4 种特殊的移动方式 
        for(int i=0;i<4;i++) 
        { 
            // 计算新的节点坐标 
            int xx=temp.x+ex[i]; 
            int yy=temp.y+ey[i]; 
            // 判断新节点是否越界 
            if(xx<1||yy<1||xx>(n+1)||yy>(n+1)) continue; 
            // 如果新节点已经被访问过(a[xx][yy] 不为 -1),则跳过 
            if(a[xx][yy]!=(-1)) continue; 
            // 更新新节点的步数为当前节点步数加 1 
            a[xx][yy]=temp.step+1;  
            // 将新节点加入队列 
            q.push(node{xx,yy,temp.step+1});  
        } 
    } 
} 

// 从起点出发进行第二次广度优先搜索 
// 目的是找到从起点到第一次搜索中标记的节点的最短路径 
void bfs2() 
{ 
    // 当队列不为空时,继续搜索 
    while(!q.empty())  
    { 
        // 取出队列的队首元素 
        node temp=q.front();  
        q.pop();  
        // 如果当前节点是第一次搜索中标记的节点 
        if(a[temp.x][temp.y]!=(-1)) 
            // 更新最短路径长度 
            ans=min(ans,(temp.step+a[temp.x][temp.y]));  
        // 遍历马的 8 种常规移动方式 
        for(int i=0;i<8;i++) 
        { 
            // 计算新的节点坐标 
            int xx=temp.x+dx[i]; 
            int yy=temp.y+dy[i]; 
            // 判断新节点是否越界 
            if(xx<1||yy<1||xx>(n+1)||yy>(n+1)) continue; 
            // 如果新节点已经被访问过,则跳过 
            if(vis[xx][yy]) continue; 
            // 标记新节点为已访问 
            vis[xx][yy]=1; 
            // 将新节点加入队列 
            q.push(node{xx,yy,temp.step+1});  
        } 
    } 
} 

int main() 
{ 
    cin>>n>>xa>>ya>>xb>>yb; 
    swap(xa,ya),swap(xb,yb); 
    xa=n-xa+1,ya++; 
    xb=n-xb+1,yb++; 
    memset(a,(-1),sizeof(a)); 
    a[xb][yb]=0;    
    q.push(node{xb,yb,0});  
    // 从终点出发进行第一次广度优先搜索 
    bfs1(); 
    while(!q.empty())  q.pop();  
    vis[xa][ya]=1; 
    q.push(node{xa,ya,0});  
    // 从起点出发进行第二次广度优先搜索 
    bfs2(); 
    // 如果最短路径长度仍然是初始值 1e9,表示无法到达终点 
    if(ans==1e9) cout<<"-1"; 
    else cout<<ans; 
    return 0; 
} 

python 代码:

注:此代码为 AI 转换得来,仅供参考。

from collections import deque 

def main():
    import sys 
    input = sys.stdin.read().split() 
    n = int(input[[0]()][[1]()][[5]()][[1]()][[1]()][[1]()][[1]()][[1]()] * (n+2) for _ in range(n+2)]
    vis =  * (n+2) for _ in range(n+2)]

    ex = [2, 2, -2, -2]
    ey = [2, -2, 2, -2]

    dx = [2, 2, 1, 1, -1, -1, -2, -2]
    dy = [1, -1, 2, -2, 2, -2, 1, -1]

    a[xb][yb] = 0 
    q = deque()
    q.append((xb,  yb, 0))

    while q:
        x, y, step = q.popleft() 
        for i in range(4):
            xx = x + ex[i]
            yy = y + ey[i]
            if 1 <= xx <= n+1 and 1 <= yy <= n+1 and a[xx][yy] == -1:
                a[xx][yy] = step + 1 
                q.append((xx,  yy, step + 1))

    ans = float('inf')
    vis[xa][ya] = True 
    q = deque()
    q.append((xa,  ya, 0))

    while q:
        x, y, step = q.popleft() 
        if a[x][y] != -1:
            ans = min(ans, step + a[x][y])

        for i in range(8):
            xx = x + dx[i]
            yy = y + dy[i]
            if 1 <= xx <= n+1 and 1 <= yy <= n+1 and not vis[xx][yy]:
                vis[xx][yy] = True 
                q.append((xx,  yy, step + 1))

    print(-1 if ans == float('inf') else ans)

if __name__ == "__main__":
    main()

结束!