骑士游历问题问题
Problem Statement:
问题陈述:
There is a chessboard of size N×M and starting position (sx, sy) and destination position (dx,dy). You have to find out how many minimum numbers of moves a knight goes to that destination position?
有一个大小为N×M的棋盘,其起始位置(sx,sy)和目标位置(dx,dy) 。 您必须找出一个骑士去那个目的地位置的最小移动次数?
Example:
例:
Input:
输入:
Check the above example...
检查上面的例子...
If the source position is (5,5) and the destination position is (3,2).
Then the path count is 3.
如果源位置是(5,5)而目标位置是(3,2) 。
那么路径计数为3 。
Algorithm:
算法:
To solve this problem we follow this approach:
为了解决这个问题,我们采用以下方法:
We use queue data structure and initialize it with the starting position and a map data structure to count the steps where the key is position and value is step count.
我们使用队列数据结构,并使用起始位置和地图数据结构对其进行初始化,以计算步数,其中键是位置,值是步数。
Then we pop the top position and push all the possible positions that are reached from that position (a knight moves 2 steps at any direction and then one step left or right) and increase the step count of the popped position by one.
然后,我们弹出顶部位置,并从该位置推动到达所有可能的位置(骑士在任意方向上移动2步,然后向左或向右移动1步),并将弹出位置的步数增加1。
We repeat step 2 until we reach the destination position and the first value is the minimum value.
重复步骤2,直到到达目标位置,并且第一个值是最小值。
骑士步行问题的C ++实现 (C++ Implementation for Knight walk problem)
#include <bits/stdc++.h>
using namespace std;
int num_x[] = { -2, -2, -1, 1, 2, 2, 1, -1 };
int num_y[] = { -1, 1, 2, 2, 1, -1, -2, -2 };
bool isvalid(int r, int c, int row, int col)
{
return (row >= 0 && row < r && col >= 0 && col < c);
}
int count(int r, int c, int sx, int sy, int dx, int dy)
{
queue<pair<pair<int, int>, int> > q;
set<pair<int, int> > st;
q.push(make_pair(make_pair(sx, sy), 0));
while (!q.empty()) {
pair<pair<int, int>, int> p = q.front();
st.insert(make_pair(sx, sy));
if (p.first.first == dx && p.first.second == dy) {
return p.second;
}
q.pop();
for (int i = 0; i < 8; i++) {
int row = p.first.first + num_x[i];
int col = p.first.second + num_y[i];
if (isvalid(r, c, row, col) && st.find(make_pair(row, col)) == st.end()) {
st.insert(make_pair(row, col));
int temp = p.second + 1;
q.push(make_pair(make_pair(row, col), temp));
}
}
}
return -1;
}
int main()
{
int r, c;
cout << "Row: ";
cin >> r;
cout << "Col: ";
cin >> c;
int sx, sy, dx, dy;
cout << "Staring position : ";
cin >> sx >> sy;
cout << "Destination position : ";
cin >> dx >> dy;
cout << "Steps :";
cout << count(r, c, sx - 1, sy - 1, dx - 1, dy - 1) << endl;
return 0;
}
Output
输出量
Row: 5
Col: 5
Staring position : 5 5
Destination position : 3 2
Steps :3
翻译自: https://www.includehelp.com/icp/knight-walk-problem.aspx
骑士游历问题问题