Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

解题思路:

经典的NP问题,采用Dancing Links可以优化算法,参考链接:https://www.ocf.berkeley.edu/~jchu/publicportal/sudoku/sudoku.paper.html

本题方法多多,优化算法也是多多,本例仅给出最简单的DFS暴力枚举算法。

JAVA实现如下:

static public void solveSudoku(char[][] board) {
int count = 0;
for (int i = 0; i < board.length; i++)
for (int j = 0; j < board[0].length; j++)
if (board[i][j] == '.')
count++;
dfs(board, count);
} public static int dfs(char[][] board, int count) {
if (count == 0)
return 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '.') {
for (int k = 1; k <= 10; k++) {
if (k == 10)
return count;
board[i][j] = (char) ('0' + k);
if (!isValid(board, i, j))
board[i][j] = '.';
else {
count--;
count = dfs(board, count);
if (count == 0)
return count;
count++;
board[i][j] = '.';
}
}
}
}
}
return count;
} static public boolean isValid(char[][] board, int row, int col) {
HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();
for (int j = 0; j < board[0].length; j++) {
if (board[row][j] != '.') {
if (hashmap.containsKey(board[row][j]))
return false;
hashmap.put(board[row][j], 1);
}
} hashmap = new HashMap<Character, Integer>();
for (int i = 0; i < board.length; i++) {
if (board[i][col] != '.') {
if (hashmap.containsKey(board[i][col]))
return false;
hashmap.put(board[i][col], 1);
}
} hashmap = new HashMap<Character, Integer>();
int rowTemp = (row / 3) * 3;
int colTemp = (col / 3) * 3; for (int k = 0; k < 9; k++) {
if (board[rowTemp + k / 3][colTemp + k % 3] != '.') {
if (hashmap
.containsKey(board[rowTemp + k / 3][colTemp + k % 3]))
return false;
hashmap.put(board[rowTemp + k / 3][colTemp + k % 3], 1);
}
}
return true;
}

最新文章

  1. YII 的源码分析(三)
  2. WebResource.axd 404 错误
  3. Web服务器amp搭建
  4. Design T-Shirt 分类: HDU 2015-06-26 11:58 7人阅读 评论(0) 收藏
  5. 在android中进行视频的分割
  6. “Cache-control”常见的取值有private、no-cache、max-age、must-revalidate等
  7. IE下onchange事件不立即执行
  8. java数据结构--线性结构
  9. C语言 - 预编译
  10. 关于sqlmap的一些命令
  11. SpringCloud系列九:SpringCloudConfig 基础配置(SpringCloudConfig 的基本概念、配置 SpringCloudConfig 服务端、抓取配置文件信息、客户端使用 SpringCloudConfig 进行配置、单仓库目录匹配、应用仓库自动选择、仓库匹配模式)
  12. mongo固定集合
  13. Python和Mysql、Nginx
  14. react面试问题总结
  15. HTML表格元素
  16. 【062新题】OCP 12c 062出现大量新题-15
  17. 第一个spring冲刺
  18. 剑指offer——面试题30:包含min函数的栈
  19. 使用 dataview 组件制作一览表
  20. ASP.NET Core 2.2 基础知识(十五) Swagger

热门文章

  1. BZOJ-2186 沙拉公主的困惑 线性筛(筛筛筛)+线性推逆元
  2. ExtJS入门教程04,这是一个超级好用的grid
  3. c3p0配置详解
  4. PHP输出表格的方法
  5. P、NP、NPC、NP-Hard问题
  6. 织梦DedeCMS首页调用单页文档内容的方法
  7. 一排cell就第一个cell要点两次才响应,其他的cell都点一下就响应
  8. WebSocket 基本函数
  9. Shell脚本获得变量值作为新变量一部分的值
  10. httpModules与httpHandlers之httpModules(转载)