当前位置:网站首页>棋盘染色问题
棋盘染色问题
2022-08-08 04:46:00 【小卢要刷力扣题】
前言
N * M的棋盘
每种颜色的格子数必须相同的
上下左右的格子算相邻
相邻格子染的颜色必须不同
所有格子必须染色
返回至少多少种颜色可以完成任务
解题思路
写暴力方法观察规律
尝试1种颜色能不能完成
尝试2种颜色能不能完成
最多有n*m种
public static int minColors(int N, int M) {
// 颜色数量是i
for (int i = 2; i < N * M; i++) {
int[][] matrix = new int[N][M];
// 下面这一句可知,需要的最少颜色数i,一定是N*M的某个因子
if ((N * M) % i == 0 && can(matrix, N, M, i)) {
return i;
}
}
return N * M;
}
// 在matrix上染色,返回只用pNum种颜色是否可以做到要求
public static boolean can(int[][] matrix, int N, int M, int pNum) {
int all = N * M;
int every = all / pNum;
ArrayList<Integer> rest = new ArrayList<>();
rest.add(0);
for (int i = 1; i <= pNum; i++) {
rest.add(every);
}
return process(matrix, N, M, pNum, 0, 0, rest);
}
public static boolean process(int[][] matrix, int N, int M, int pNum, int row, int col, List<Integer> rest) {
if (row == N) {
return true;
}
if (col == M) {
return process(matrix, N, M, pNum, row + 1, 0, rest);
}
int left = col == 0 ? 0 : matrix[row][col - 1];
int up = row == 0 ? 0 : matrix[row - 1][col];
for (int color = 1; color <= pNum; color++) {
if (color != left && color != up && rest.get(color) > 0) {
int count = rest.get(color);
rest.set(color, count - 1);
matrix[row][col] = color;
if (process(matrix, N, M, pNum, row, col + 1, rest)) {
return true;
}
rest.set(color, count);
matrix[row][col] = 0;
}
}
return false;
}


根据输出规律,我们不难推出是最小颜色是N*M最小的质数因子
边栏推荐
- 初出茅庐的小李第115篇博客项目笔记之国产GD32F103RCT6基础工程创建
- Servlet---ServletConfig类使用介绍
- 基于MindSpore框架的数字调制信号盲识别研究
- vulnhub-DC-3 drone penetration record
- L3-007 天梯地图(测试点2卡住了可以看下)
- Week 8 Transformer Language Models and Implications
- The only OpenCyphal/UAVCAN tutorial in the whole network (11) Write a Cyphal protocol parsing tool with candump and gawk tools
- Exercise equipment responsive pbootcms template class web site
- [Graph Basics] How to Define Few-Shot Learning on Heterogeneous Graphs: Heterogeneous Graph Few-Shot Learning
- MySQL——索引与事务
猜你喜欢
随机推荐
【Redis】Redis学习——事务
L3-006 迎风一刀斩
硬盘基础知识
Open3D ICP精配准(使用鲁棒性核函数)
强网杯 2019-随便注 (堆叠注入)
国内最主流的5大项目工时管理系统
Sequence table (below)
【论文分享】异质图上的小样本学习:HG-Meta: Graph Meta-learning over Heterogeneous Graphs
L3-007 天梯地图(测试点2卡住了可以看下)
leetcode 112.路经总和 递归
C语言框架FreeSwitch自定义事件介绍与使用示例
MySQL中CHAR_LENGTH()和LENGTH()的区别
MySQL——索引与事务
MYSQL export data dictionary
leetcode-isomorphic string judgment
A line of code counts the number of occurrences of the specified string in the text
The difference between CHAR_LENGTH() and LENGTH() in MySQL
KDD‘22推荐系统论文梳理(24篇研究&36篇应用论文)
leetcode: 874. Simulate a walking robot
B. Reverse Binary Strings









