랜덤으로 9*9 크기의 스도쿠를 구현해보았습니다. 

스도쿠를 만드는 조건은 다음과 같습니다.

1.가로조건을 만족

2.세로조건을 만족

3.3*3조건을 만족 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.Random;
 
public class Main {
    private static int SIZE = 10;
    public static int matrix[][] = new int[SIZE][SIZE];
 
    public static void main(String[] args) {
        for (int i = 1; i < SIZE; i++) {
            for (int j = 1; j < SIZE; j++) {
                matrix[i][j] = 0;
            }
        }
        fill(0);
    }
    public static void fill(int cnt){
        if(cnt==81){
            for(int i=1;i<=9;i++){
                for(int j=1;j<=9;j++){
                    System.out.print(matrix[i][j]+"");
                }
                System.out.println();
            }
            System.exit(0);
        }
        int y=0;
        int x=0;
        boolean Check=true;
        for(int i=1;i<=9;i++){
            for(int j=1;j<=9;j++){
                if(matrix[i][j]==0){
                    y=i;
                    x=j;
                    Check=false;
                    break;
                }
            }
            if(!Check) break;
        }
        if(Check) return ;
 
        for(int n=1;n<=9;n++){
            Random r=new Random();
            int num=r.nextInt(9)+1;
            if(isSafe(num,y,x)){
                matrix[y][x]=num;
                fill(cnt+1);
                matrix[y][x]=0;
            }
        }
    }
 
    public static boolean isSafe(int n, int y, int x) {
        if (checkRow(y, n) && checkCol(x, n) && checkBox(y, x, n))
            return true;
 
        return false;
    }
 
    public static boolean checkCol(int x, int n) {
        for (int i = 1; i <= 9; i++) {
            if (matrix[i][x] == n)
                return false;
        }
        return true;
    }
 
    public static boolean checkRow(int y, int n) {
        for (int j = 1; j <= 9; j++) {
            if (matrix[y][j] == n)
                return false;
        }
        return true;
    }
    public static boolean checkBox(int y,int x,int n){
        int row = ((int) Math.ceil(y / 3.0- 1* 3 + 1;
        int col = ((int) Math.ceil(x / 3.0- 1* 3 + 1;
        for (int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                if(matrix[row+i][col+j]==n)
                    return false;
            }
        }
        return true;
    }
}
cs


+ Recent posts