力扣每日一题5-18

class Solution {

public int colorTheGrid(int m, int n) {

// 每一列可能的状态总数 每个单元有3可能

int totalState = 1;

for (int i = 0; i < m; ++i) totalState *= 3;

// pre[k] 代表前一轮dp 状态为k 的方案总数

int [] pre = new int [totalState];

// 初始化合法填色 的 方案数为1

for (int state = 0; state < totalState; ++state) {

if (checkCol(state, m)) pre[state] = 1;

}

for (int i = 1; i < n; ++i) {

int [] cur = new int [totalState];

// 枚举可能的转移

for (int preState = 0; preState < totalState; ++preState) {

if (pre[preState] == 0) continue;

for (int curState = 0; curState < totalState; ++curState) {

// 行和列的填色都满足题设

if (checkCol(curState, m) && checkRow(preState, curState, m)) {

cur[curState] = addWithMode(cur[curState], pre[preState]);

}

}

}

pre = cur;

}

int planNum = 0;

for (int state = 0; state < totalState; ++state) {

planNum = addWithMode(planNum, pre[state]);

}

return planNum;

}

private boolean checkCol(int state, int m) {

int prevCeilColor = -1;

while (m-- > 0) {

if (state % 3 == prevCeilColor) {

return false;

}

prevCeilColor = state % 3;

state /= 3;

}

return true;

}

private boolean checkRow(int pre, int cur, int m) {

while (m-- > 0) {

if (pre % 3 == cur % 3) return false;

pre /= 3;

cur /= 3;

}

return true;

}

private int addWithMode(int a, int b) {

int mode = (int) 1E9 + 7;

return (a + b) % mode;

}

}

相关推荐
寻星探路34 分钟前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
你撅嘴真丑3 小时前
第九章-数字三角形
算法
曹牧3 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
uesowys3 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder3 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮3 小时前
AI 视觉连载1:像素
算法
爬山算法4 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
智驱力人工智能4 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
kfyty7254 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎4 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven