问题遇到的现象和发生背景
蓝桥杯剪邮票问题,为什么算出来的是222而不是116。简单的dfs思路,自我感觉没错,但是结果就是不对
题目链接:https://blog.csdn.net/weixin_48203907/article/details/109498229
问题相关代码,请勿粘贴截图
#include<iostream>
using namespace std;
int use[3][4], chos[5], dx[4] = { 0,-1,1,0 }, dy[4] = { -1,0,0,1 }, n = 0;
void dfs(int step,int start);
bool IsRight(int a);
int main()
{
int i, j;
dfs(0,0);
cout << n;
return 0;
}
void dfs(int step,int start)
{
int i, j;
if (step == 5)
{
for (i = 0;i < 5;i++)
{
if (IsRight(i) == false)
return;
}
n++;
return;
}
else
{
for (i = start;i < 12;i++)
{
if (use[i / 4][i % 4] == 0)
{
chos[step] = i;
use[i / 4][i % 4] = 1;
dfs(step + 1,i+1);
use[i / 4][i % 4] = 0;
}
}
}
}
bool IsRight(int a)
{
int x, y, i;
for (i = 0;i < 4;i++)
{
x = (chos[a] % 4) + dx[i];
y = (chos[a] / 4) + dy[i];
if (x >= 0 && y >= 0 && x < 4 && y < 3)
if (use[y][x] == 1)
return true;
}
return false;
}
运行结果及报错内容
222
我的解答思路和尝试过的方法
1.dfs升序排列。
2.检测每张邮票有无相邻邮票。