Sudoku , 华为

dfs找到解,return true, 不需要继续找了,不然回溯将恢复整个棋盘。 或者, 记录下该解,继续找下一个解(如果存在多解, 但一般不需要)。

import java.util.*;
public class Main {
    static int[][] grid;
    static boolean[][] rows, cols;
    static boolean[][][] cell;
    static boolean dfs(int x, int y) {
        if(y == 9) {
            x ++; y = 0;
        }
        if(x == 9) return true;
        if(grid[x][y] != 0) 
            return dfs(x,y+1);
        for(int i=0; i < 9; i++) {
            if(!rows[x][i] && !cols[y][i] && !cell[x/3][y/3][i]) {
                grid[x][y] = i+1;
                rows[x][i] = cols[y][i] = cell[x/3][y/3][i] = true;
                if(dfs(x, y+1)) return true;
                rows[x][i] = cols[y][i] = cell[x/3][y/3][i] = false;
                grid[x][y] = 0;
            }
        }
        return false;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = 9;
            grid = new int[n][n];
            rows = new boolean[n][n];
            cols = new boolean[n][n];
            cell = new boolean[3][3][n];
            for(int i=0; i < n; i++)
                for(int j=0; j < n; j++) {
                    grid[i][j] = sc.nextInt();
                    if(grid[i][j] != 0) {
                        int u = grid[i][j] - 1;
                        rows[i][u] = cols[j][u] = cell[i/3][j/3][u] = true;
                    }
                }
            dfs(0, 0);
            for(int i=0; i < n; i++) {
                for(int j=0; j < n-1; j++)
                    System.out.print(grid[i][j] + " ");
                System.out.println(grid[i][n-1]);
            }
        }
    }
}

原文地址:https://www.cnblogs.com/lixyuan/p/13272597.html