思路:这是一道广搜(bfs)水题!!!
其实这一题和洛谷p1443马的遍历是一样的只不过是在马走日字的基础上增添了马走田字的规则
分别从两个马的位置一直到搜到(1,1)为止,在过程中累加步数,根据广搜层层拓展的原理可知最先搜到(1,1)时一定是最优解
代码:
#include<bits/stdc++.h>
using namespace std;
int dx[13] = { 1,1,2,2,2,2,-1,-1,-2,-2,-2,-2 };//用数组来代替走日字和走田字的规则
int dy[13] = { -2,2,-2,-1,1,2,-2,2,-1,1,-2,2 };
int vis[105][105];
int x1, y2;
struct pos
{
int x, y, step;//结构体定义位置和步数
};
void bfs()
{
pos cur, nex;//结构体变量
queue<pos>qu;//队列
cur.x = x1, cur.y = y2, cur.step = 0;
vis[cur.x][cur.y] = 1;
qu.push(cur);
while (qu.empty() == false)//队列为空就退出了
{
cur = qu.front();
qu.pop();
for (int i = 0; i < 13; i++)
{
nex.x = cur.x + dx[i];
nex.y = cur.y + dy[i];
if (nex.x > 0 && nex.x <= 100 && nex.y > 0 && nex.y <= 100 && vis[nex.x][nex.y] == 0)//判断边界 因为题目是不给边界的所以我们自己开大点
{
vis[nex.x][nex.y] = 1;
nex.step = cur.step + 1;
qu.push(nex);
if (nex.x == 1 && nex.y == 1)//走到1 1就输出步数并返回
{
cout << nex.step << '\n';
return;
}
}
}
}
return;
}
int main()
{
ios::sync_with_stdio(false);//给cin提速
cin.tie(0);
while (cin >> x1 >> y2)//多组输入
{
memset(vis, 0, sizeof(vis));//一定要初始化vis数组 我就wa了一次
if (x1 == 1 && y2 == 1)//提前判断
{
cout << 0 << '\n';
continue;
}
bfs();
}
return 0;
}
下面是p1143 马的遍历
思路和上面一模一样
#include<bits/stdc++.h>
using namespace std;
int n, m, x, y;
int vis[404][404], t[404][404];
int dx[8] = { -2,-2,2,2,1,-1,1,-1 };
int dy[8] = { -1,1,-1,1,2,-2,-2,2 };
struct pos
{
int nx, ny;
};
int main()
{
memset(t, -1, sizeof(t));
queue<pos>qu;
pos cur, nex;
cin >> n >> m >> x >> y;
vis[x][y] = 1;
t[x][y] = 0;
cur.nx = x;
cur.ny = y;
qu.push(cur);
while (qu.empty() == false)
{
cur = qu.front();
qu.pop();
for (int i = 0; i < 8; i++)
{
nex.nx = cur.nx + dx[i];
nex.ny = cur.ny + dy[i];
if (nex.ny > 0 && nex.ny <= m && nex.nx > 0 && nex.nx <= n && vis[nex.nx][nex.ny] == 0)
{
t[nex.nx][nex.ny] = t[cur.nx][cur.ny] + 1;
vis[nex.nx][nex.ny] = 1;
qu.push(nex);
}
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
printf("%-5d", t[i][j]);
}
cout << '\n';
}
return 0;
}
感谢你的观看如果帮助点个赞谢谢!!!