题目:
https://www.luogu.com.cn/problem/P2385
题目看仔细,是M行N列.八个方向数组依靠M1,M2,所以初始化方向数组要在主函数里面,传入bfs函数里。
#include <iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct Node{int x;int y;int step;
};
queue <Node> q;
int N,M,M1,M2;
int stl [31][31];
int map[31][31];
int bfs(int x,int y ,int step,int dx[],int dy[])//传入数组 数组也可以这样传int bfs(int x,int y ,int step,int *dx,int *dy)
{Node start = {x,y,step};q.push(start);//压入队首 stl[x][y] = true;//标记已经过 while(!q.empty()){int x = q.front().x;//取出队首三个数据 int y = q.front().y;int step = q.front().step;if(map[x][y] == 4){return step;}for(int k = 0 ; k < 8 ; k++){int tx = x + dx[k];int ty = y + dy[k];if(tx >= 1 && tx <= 30 && ty >= 1 && ty <= 30 && stl[tx][ty] == false && (map[tx][ty] == 4 || map[tx][ty] == 1))//边界条件 {stl[tx][ty] = true;Node nowpos = {tx,ty,step+1};q.push(nowpos);}}q.pop();}return -1;
}
int main()
{cin >> M >> N >> M1 >> M2;int ans;bool stl[100][100];int dx[8]={M2,M1,M1,-M2,-M2,-M1,-M1,M2};//初始化这八个方向 int dy[8]={M1,M2,-M2,M1,-M1,-M2,M2,-M1};for(int i = 1 ; i <= M ; i++){for(int j = 1 ; j <= N ; j++){cin >> map[i][j];}}for(int i = 1 ; i <= M ; i++){for(int j = 1 ; j <= N ; j++){if(map[i][j] == 3 && stl[i][j] == false){ans = bfs(i,j,0,dx,dy);break; }}}cout << ans;return 0;
}