马走日算法-回溯
1.马走日走到目标节点最少的步数
#include<iostream>
#include<queue>
#include<functional>
#include<stack>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<unordered_map>
#include<memory>
using namespace std;
int dst_x = 3;
int dst_y = 2;
//表示的是棋盘大小
int m = 5;
int n = 5;
int min_bushu = INT_MAX;//最少步数
void mazouri_zuishao(int x, int y, vector<vector<int>>& flag, int ans)
{
int dx[8] = { -2,-1,1,2,2,1,-1,-2 };
int dy[8] = { 1,2,2,1,-1,-2,-2,-1 }; //方便表示吓一跳
int nx;
int my;
if (x == dst_x&&y == dst_y)
{
min_bushu = ans < min_bushu ? ans : min_bushu;
}
for (int i = 0; i < 8; ++i)
{
nx = x + dx[i];
my = y + dy[i];
if (nx >= 1 && nx <= n&&my >= 1 && my <= m&&flag[my][nx] == 0)
{
flag[my][nx] = 1;
mazouri_zuishao(nx, my, flag, ans + 1);
flag[my][nx] = 0;
}
}
}
int main()
{
int ans = 0;
int count = 0;
vector<vector<int>> bianli(m + 1, vector<int>(n + 1, 0));
bianli[1][1] = 1;
mazouri_zuishao(1, 1, bianli, ans);
cout << min_bushu << endl;
return 0;
}
马走日遍历所有的棋盘节点,计算所有路径的条数
#include<iostream>
#include<queue>
#include<functional>
#include<stack>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<unordered_map>
#include<memory>
using namespace std;
int dst_x = 3;
int dst_y = 2;
//表示的是棋盘大小
int m = 5;
int n = 4;
void mazouri(int x, int y, vector<vector<int>> &bianli, int ans, int& count)
{
int dx[8] = { -2,-1,1,2,2,1,-1,-2 };
int dy[8] = { 1,2,2,1,-1,-2,-2,-1 }; //方便表示吓一跳
int nx;
int my;
if (ans == m*n)
{
++count;
return;
}
for (int i = 0; i < 8; ++i)
{
nx = x + dx[i];
my = y + dy[i];
if (nx >= 1 && nx <= n&&my >= 1 && my <= m&&bianli[my][nx] == 0)
{
bianli[my][nx] = 1;
mazouri(nx, my, bianli, ans + 1, count);
bianli[my][nx] = 0;
}
}
}
int main()
{
int ans = 1;
int count = 0;
vector<vector<int>> bianli(m + 1, vector<int>(n + 1, 0));
bianli[1][1] = 1;
mazouri(1, 1, bianli, ans, count);
cout <<count << endl;
return 0;
}
主要思想都是回溯算法只不过是一些约束条件不一样