Java解数独--世界最难数独

2014-11-24 09:56:16 · 作者: · 浏览: 0

在其他地方看到这个方法,稍微修改了一下,贴出来

用到Shudu和Grid两个类,

运行 Shudu里的main方法,

我读取的是本地文件,据说这个是神马大师设计的最难数独,大家可以自行修改

package shudu;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class Shudu {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date begin=dfs.parse(dfs.format(new Date()));
        
    	String arg = "C:/shudu.txt";
        FileReader rd = new FileReader(arg);
        while (true) {
            Grid grid = Grid.create(rd);
            if (grid == null) {
                break;
            }
            List solutions = new ArrayList();
            
            solve(grid, solutions);

            printSolutions(grid, solutions);   
        }
        
        Date end=dfs.parse(dfs.format(new Date()));
        long between=end.getTime()-begin.getTime();
        System.out.println("use Time:"+between+"ms");
    }

    private static void solve(Grid grid, List solutions) {

        if (solutions.size() >= 2) {
            return;
        }

        int loc = grid.findEmptyCell();

        if (loc < 0) {
            solutions.add(grid.clone());
            return;
        }

        for (int n=1; n<10; n++) {
            if (grid.set(loc, n)) {
                solve(grid, solutions);

                grid.clear(loc);
            }
        }
    }

    private static void printSolutions(Grid grid, List solutions) {
        System.out.println("Original");
        System.out.println(grid);

        if (solutions.size() == 0) {
            System.out.println("Unsolveable");
        } else if (solutions.size() == 1) {
            System.out.println("Solved");
        } else {
            System.out.println("At least two solutions");
        }

        for (int i=0; i 
 
package shudu;

import java.io.Reader;


public class Grid implements Cloneable {
    int[] cells = new int[81];

    int[] colsSet = new int[9];

    int[] rowsSet = new int[9];

    int[] subgridSet = new int[9];

    
    public static Grid create(Reader rd) throws Exception {
        Grid grid = new Grid();

       
        for (int loc=0; loc= 0 && ch != '\n' && ch != '\r') {
                    ch = rd.read();
                }
            } else if (ch >= '1' && ch <= '9') {

                grid.set(loc, ch-'0');
                loc++;
            } else if (ch == '.' || ch == '0') {

                loc++;
            }
        }
        return grid;
    }


    public int findEmptyCell() {
        for (int i=0; i