首页 >Java >java教程 > 正文

数独小算法的实例详解

原创2020-10-26 12:55:370267
class SudokuMatrix {

    private int[][] matrix = new int[][] {
            {0, 5, 0, 6, 0, 1, 0, 0, 0},
            {0, 0, 7, 0, 9, 0, 0, 2, 0},
            {3, 0, 0, 0, 0, 4, 0, 0, 1},
            {9, 0, 0, 0, 0, 0, 1, 3, 0},
            {0, 0, 8, 0, 5, 0, 7, 0, 0},
            {0, 2, 6, 0, 0, 0, 0, 0, 8},
            {7, 0, 0, 9, 0, 0, 0, 0, 5},
            {0, 9, 0, 0, 4, 0, 3, 0, 0},
            {0, 0, 0, 2, 0, 8, 0, 1, 0},
    };

    public void run(){
        calc();
    }


    private void calc() {

        int[] coordinate = getNextData();
        int m = coordinate[0];
        int n = coordinate[1];

        for (int k = 1; k <= 9; k++) {
            if(checkNumber(m,n,k)) {
                matrix[m][n] = k;

                //System.out.println( m + "," + n + " with " + k );

                if ( getNextData() == null ) {
                    print(matrix);
                }
                else {
                    calc();
                }
            }

        }


        matrix[m][n] = 0;
    }

    private int[] getNextData(){

        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                if (matrix[row][col] == 0) {
                    int[] coordinateOfEmptySquare = {row, col};
                    return coordinateOfEmptySquare;
                }
            }
        }

        return null;
    }


    private boolean checkNumber(int row, int col, int n) {
        for (int i = 0; i < 9; i++) {
            if (matrix[row][i] == n || matrix[i][col] == n) {
                return false;
            }
        }

        int[] leftTop = {row - (row % 3), col - (col % 3)};

        for (int r = leftTop[0]; r <= leftTop[0] + 2; r++) {
            for (int c = leftTop[1]; c <= leftTop[1] + 2; c++) {
                if (matrix[r][c] == n) {
                    return false;
                }
            }
        }

        return true;
    }

    public void print(int[][] grid) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                System.out.print(grid[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
    }

}

以上就是数独小算法的实例详解的详细内容,更多请关注php学习网其它相关文章!

phpStudy Linux 面板(小皮面板)
  • 相关标签:Java 通过 测试 算法
  • 本文原创发布php学习网,转载请注明出处,感谢您的尊重!
  • 相关文章

    相关视频


    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论
  • 专题推荐

    作者信息

    php学习网

    认证0级讲师

    推荐视频教程
  • javascript初级视频教程javascript初级视频教程
  • jquery 基础视频教程jquery 基础视频教程
  • 视频教程分类