zoukankan      html  css  js  c++  java
  • Java for LeetCode 037 Sudoku Solver

    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;
    	}
    
  • 相关阅读:
    mongodb复制集搭建
    mongodb分片集群搭建
    mongodb安装、运行
    吉他“和弦”是什么?
    NoSQL 简介
    淘汰算法 LRU、LFU和FIFO
    Java遍历Map对象的四种方式
    终于搞懂了shell bash cmd...
    如何为openwrt生成补丁
    linux内核启动时报错ubi0 error: validate_ec_hdr: bad data offset 256, expected 128
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4488727.html
Copyright © 2011-2022 走看看