问题
小明有一张m*n的好习惯记录卡,记录每一天的好习惯目标达成度(数字0-9表示)。某天目标完成达成,就在当天的格子里写上数字6,目标没有完全达成就写上一个小于6的数字(0-5),目标超额完成就写上一个大于6的数字(7-9)。记录卡上如果能找到一条长度为3的路径并且路径上的三个数字都大于等于6(这里的路径是指从某个格子出发,可以向左、右、上、下格子移动,并且不能重复经过一个格子),则小明就能得到一个“666”奖励。
请你帮小明统计下他总共能得到多少“666”奖励。
输入格式:
输入第一行给出两个正整数m,n(1=<m,n<=100),随后是m行,每行包含n个0-9之间的数字。
输出格式:
先输出m行,每行包括n个整数,代表从当前格子出发得到的“666”奖励个数,中间用空格分割,最后一个数字后面不带空格。然后再在下一行输出得到的“666”奖励总数。
输入样例:
3 3
6 6 7
3 8 3
7 9 5
输出样例:
2 1 2
0 3 0
1 1 0
10
源代码
#include<iostream>
using namespace std;
int resource[102][102];//输入数组
int result[102][102];//保存结果的数组
int n, m;//m行,每行n个数
int backTrack(int i,int j,int undergoing,int direction) {//起始格子只有>=6才能进入
//i和j是起始格子的坐标,undergoing是经过的格子个数,direction表示方向,1代表向右,2代表向向下,3代表向左,4代表向上
int number = 0, count = 0;//number表示有符合标准的解(即所经历的2个格子均>=6),count用于记录总的解个数
if (resource[i][j + 1] >= 6 && direction != 3) {//向右移动,且不往左移
if (undergoing == 2) {//经过2个格子,到达第3个格子(算上自己)
number++;
}
else {
count += backTrack(i, j + 1, undergoing + 1, 1);//往右移,经过格子数+1
}
}
if (resource[i+1][j] >= 6 && direction != 4) {//向下移动,且不往上移
if (undergoing == 2) {//经过2个格子,到达第3个格子(算上自己)
number++;
}
else {
count += backTrack(i +1 , j, undergoing + 1, 2);//往下移,经过格子数+1
}
}
if (resource[i][j - 1] >= 6 && direction != 1) {//向左移动,且不往右移
if (undergoing == 2) {//经过2个格子,到达第3个格子(算上自己)
number++;
}
else {
count += backTrack(i, j - 1, undergoing + 1, 3);//往左移,经过格子数+1
}
}
if (resource[i-1][j] >= 6 && direction != 2) {//向上移动,且不往下移
if (undergoing == 2) {//经过2个格子,到达第3个格子(算上自己)
number++;
}
else {
count += backTrack(i - 1, j, undergoing + 1, 4);//往上移,经过格子数+1
}
}
if (undergoing == 2) {
return number;
}
else {
return count;
}
}
int main() {
int sum = 0;
cin >> m >> n;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
cin >> resource[i][j];
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (resource[i][j] >= 6)//起始格子只有>=6才能进入
result[i][j] = backTrack(i, j, 1, 0);
else
result[i][j] = 0;
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
cout << result[i][j];
if (j != n) {//最后一个数不输出空格
cout << " ";
}
sum += result[i][j];
}
cout << endl;
}
cout << sum << endl;
return 0;
}