蓝桥杯第七届省赛C语言B组第六题方格填数解题报告---DFS

版权声明:转载请注明出处:https://blog.csdn.net/qq1013459920 https://blog.csdn.net/qq1013459920/article/details/88360183

                                                  方格填数

如下的10个格子
   +--+--+--+
   |  |  |  |
+--+--+--+--+
|  |  |  |  |
+--+--+--+--+
|  |  |  |
+--+--+--+

(如果显示有问题,也可以参看【图1.jpg】)

填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)

一共有多少种可能的填数方案?

请填写表示方案数目的整数。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。

答案:1580

从左往右,从上到下搜索(0, 1) 到(2, 3)

Code:

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <map>
const static int dir[4][2] = { {-1, 0}, {-1, -1}, {0, -1}, {-1, 1}};
	/*从左往右搜索,只需判断上、左上、左、右上四个方向是否有数字相邻*/
int maps[5][5];
bool vis[15];
int res;
bool judge(int x, int y, int v) {	//判断相邻点是否有连续数字
	for (int k = 0; k < 4; ++k) {
		int fx = x + dir[k][0];
		int fy = y + dir[k][1];
		if (fx >= 0 && fx < 3 && fy >= 0 && fy < 4) {
			if (abs(v - maps[fx][fy]) == 1) {
				return false;
			}
		}
	}
	return true;
}
void dfs(int x, int y) {
	if (x == 2 && y == 3) {
		res++;
		return;
	}
	if (y == 4) {	//y到边界直接从下一行开始搜索
		x++;
		y = 0;
	}
	for (int i = 0; i <= 9; ++i) {
		if (!vis[i] && judge(x, y, i)) {
			vis[i] = true;
			maps[x][y] = i;
			dfs(x, y + 1);
			vis[i] = false;
		}
	}
}
int main(){
	for (int i = 0; i < 5; ++i) {	//初始化一个大一点的值
		for (int j = 0; j < 5; ++j) {
			maps[i][j] = 50;
		}
	}
	res = 0;
	dfs(0, 1);
	printf("%d\n", res);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq1013459920/article/details/88360183