当前位置: 首页 > java >正文

LeetCode每日一题,2025-8-31

dfs搜索解数独,重点是如何判断当前这位置的board[x][y]是否可以填数字num

public class T37 {public static void main(String[] args) {char[][] board = new char[][]{{'5', '3', '.', '.', '7', '.', '.', '.', '.'},{'6', '.', '.', '1', '9', '5', '.', '.', '.'},{'.', '9', '8', '.', '.', '.', '.', '6', '.'},{'8', '.', '.', '.', '6', '.', '.', '.', '3'},{'4', '.', '.', '8', '.', '3', '.', '.', '1'},{'7', '.', '.', '.', '2', '.', '.', '.', '6'},{'.', '6', '.', '.', '.', '.', '2', '8', '.'},{'.', '.', '.', '4', '1', '9', '.', '.', '5'},{'.', '.', '.', '.', '8', '.', '.', '7', '9'}};T37 t37 = new T37();t37.solveSudoku(board);// 输出结果for (int i = 0; i < 9; i++) {for (int j = 0; j < 9; j++) {System.out.print(board[i][j] + " ");}System.out.println();}}public void solveSudoku(char[][] board) {dfs(board, 0, 0);}// 回溯private boolean dfs(char[][] board, int row, int col) {// 如果列到头,换行if (col == 9) {return dfs(board, row + 1, 0);}// 如果行到头,说明填完了if (row == 9) {return true;}// 如果当前位置不是空格,直接跳过if (board[row][col] != '.') {return dfs(board, row, col + 1);}// 尝试填 1~9for (char c = '1'; c <= '9'; c++) {if (isValid(board, row, col, c)) {board[row][col] = c;if (dfs(board, row, col + 1)) {return true; // 找到答案就立即返回}board[row][col] = '.'; // 回溯}}return false; // 9 个都不行,返回 false}// 判断当前位置填 num 是否有效private boolean isValid(char[][] board, int row, int col, char num) {for (int i = 0; i < 9; i++) {if (board[row][i] == num) return false; // 行if (board[i][col] == num) return false; // 列if (board[(row / 3) * 3 + i / 3][(col / 3) * 3 + i % 3] == num) return false; // 3x3 宫格}return true;}
}
http://www.xdnf.cn/news/19450.html

相关文章:

  • TFS-2002《Analysis and Efficient Implementation of a Linguistic Fuzzy C-Means》
  • 【量化回测】backtracker整体架构和使用示例
  • Rsync 数据同步工具及实时同步配置
  • SAP PP中的MRP
  • 【OpenGL】LearnOpenGL学习笔记18 - Uniform缓冲对象UBO
  • 模型系列(篇三)-Llama
  • vscode克隆远程代码步骤
  • 合约服务架构-OOP 方式
  • leetcode 371 两个整数之和
  • 微软开源TTS模型VibeVoice,可生成 90 分钟4人语音
  • TFS-1996《The Possibilistic C-Means Algorithm: Insights and Recommendations》
  • 一些八股总结
  • 如何快速学习新技能
  • Redis 7.0 高性能缓存架构设计与优化
  • [Android] UI进阶笔记:从 Toolbar 到可折叠标题栏的完整实战
  • IDEA插件ApifoxHelper
  • C++ 登录状态机项目知识笔记
  • Nginx虚拟主机配置
  • CTFshow系列——命令执行web69-72
  • 数据结构 04(线性:双向链表)
  • 【大前端】React配置配置 开发(development)、生产(production)、测试(test)环境
  • 学习数据结构(15)插入排序+选择排序(上)
  • 算法——链表
  • 开源协作白板 – 轻量级多用户实时协作白板系统 – 支持多用户绘图、文字编辑、图片处理
  • 进程间通信IPC(interprocess communicate)
  • Introduction to GIS —— Chapter 4(Raster Data Model)
  • 解读IEC 60529-2013
  • MySQL 公用表达式
  • AI军团协同作战:Manus Wide Research深度解析
  • CAN数据链路层、网络层(ISO11898、15765)