禁止转载,该文章内容并非教学,仅为个人笔记。
问题描述
观察下面的加法算式:
祥 瑞 生 辉 a b c d
+ 三 羊 献 瑞 e f g b
--------------------------------------
三 羊 生 瑞 气 e f c b h
其中,相同的汉字代表相同的数字,不同的汉字代表不同的数字。
请你填写“三羊献瑞”所代表的4位数字(答案唯一)。
解题思路
其实就是寻找 a,b,c,d,e,f,g,h 这八个字母分别代表的不同数字,把所有的可能都遍历一边就肯定能找到答案。
不过要注意,算式中的 e 不能为 0。
代码实现
#include <iostream>
using namespace std;
bool IsOk();
bool Dfs(int);
int Numbers[8]; // a,b,c,d,e,f,g,h
int Original[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
bool Dfs(int index = 0)
{
if (index == 8) return IsOk();
for (auto &item: Original)
{
if (item == -1) continue;
Numbers[index] = item;
item = -1;
if (Dfs(index + 1))
return true; // 如果已经找到则无需再向下寻找
item = Numbers[index];
}
return false;
}
bool IsOk()
{
int add1 = Numbers[0] * 1000 + Numbers[1] * 100 + Numbers[2] * 10 + Numbers[3];
int add2 = Numbers[4] * 1000 + Numbers[5] * 100 + Numbers[6] * 10 + Numbers[1];
int result = Numbers[4] * 10000 + Numbers[5] * 1000 + Numbers[2] * 100 + Numbers[1] * 10 + Numbers[7];
if ((add1 + add2) == result && add2 > 999) // e 不能为 0,add2 必须是一个四位数
{
cout << add1 << " + " << add2 << " = " << result;
return true;
}
return false;
}
int main()
{
Dfs();
return 0;
}
运行结果
9567 + 1085 = 10652