广搜,搜到4以后广搜的层数就是答案。

#include<iostream>
#include<queue>

using namespace std;

const int MAXN = 50;
int G[MAXN][MAXN];
bool visit[MAXN][MAXN];
struct node{
    int x,y,cur;
};
int main()
{
    int M,N,M1,M2;
    cin >> M >> N >> M1 >> M2;
    int sx,sy,ex,ey;
    for(int i = 1 ;i <= M ; i++)
    {
        for(int j = 1 ; j <= N ; j++)
        {
            cin >> G[i][j];
            if(G[i][j]==3){sx = i;sy = j;}
            if(G[i][j]==4){ex = i;ey = j;}
        }
    }
    int dir[8][2]={{M1,M2},{-M1,M2},{M1,-M2},{-M1,-M2},
                {M2,M1},{-M2,M1},{M2,-M1},{-M2,-M1}};
    queue<node> Q;
    Q.push(node{sx,sy,0});
    visit[sx][sy]=true;
    int ans = 0;
    while(!Q.empty())
    {
        node now = Q.front();
        int x = now.x;
        int y = now.y;
        int cur = now.cur;
        if(x==ex&&y==ey)
        {
            ans = cur;
            break;
        }
        Q.pop();
        for(int i = 0 ; i < 8 ; i++)
        {
            int tx = x+dir[i][0];
            int ty = y+dir[i][1];
            if(!(tx>=1&&tx<=M)&&!(ty>=1&&ty<=N))
            {
                continue;
            }
            if((!visit[tx][ty])&&(G[tx][ty]==1||G[tx][ty]==4))
            {
                visit[tx][ty]=true;
                Q.push(node{tx,ty,cur+1});
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}