Untitled

 avatar
unknown
java
a year ago
2.7 kB
4
Indexable
public class Suduko {

    public static boolean issafe(int suduko[][], int row, int col, int digit) {

        // colum cheeck 0 to 8 vertical check if found false them
        for (int i = 0; i < suduko.length; i++) {
            if (suduko[i][col] == digit) {
                return false;
            }

        }
        // row cheeck 0 to 8 horizantal check if found false them
        for (int j = 0; j < suduko.length; j++) {
            if (suduko[row][j] == digit) {
                return false;
            }

        }

        // grid check 3*3 matrix

        int sr = (row / 3) * 3;
        int sc = (col / 3) * 3;
        for (int i = sr; i < sr + 3; i++) {
            for (int j = sc; j < sc + 3; j++) {
                if (suduko[i][j] == digit) {
                    return false;
                }

            }

        }

        return true;

    }

    public static boolean sudukosolver(int suduko[][], int row, int col) {
//atlast row 9 n-1 true
        if (row == 9) {
            return true;
        }

        //col+1
        int nextrow = row, nextcol = col + 1;
        if (col + 1 == 9) {
            nextrow = row + 1;
            nextcol = 0;
        }

        if (suduko[row][col] != 0) {
            return sudukosolver(suduko, nextrow, nextcol);
        }

        for (int i = 1; i <= suduko.length; i++) {
            if (issafe(suduko, row, col, i)) {
                suduko[row][col] = i;
                if (sudukosolver(suduko, nextrow, nextcol)) {
                    return true;
                }
                suduko[row][col] = 0;
            }
        }

        return false;

    }

    public static void printsuduko(int suduko[][]) {
        for (int i = 0; i < suduko.length; i++) {
            for (int j = 0; j < suduko.length; j++) {
                System.out.print(suduko[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int suduko[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
                { 5, 2, 0, 0, 0, 0, 0, 0, 0 },
                { 0, 8, 7, 0, 0, 0, 0, 3, 1 },
                { 0, 0, 3, 0, 1, 0, 0, 8, 0 },
                { 9, 0, 0, 8, 6, 3, 0, 0, 5 },
                { 0, 5, 0, 0, 9, 0, 6, 0, 0 },
                { 1, 3, 0, 0, 0, 0, 2, 5, 0 },
                { 0, 0, 0, 0, 0, 0, 0, 7, 4 },
                { 0, 0, 5, 2, 0, 6, 3, 0, 0 } };

        if (sudukosolver(suduko, 0, 0)) {
            System.out.println("solution exist");
            printsuduko(suduko);
        } else {
            System.out.println("solution doesnot exist");
        }
    }
}
Editor is loading...
Leave a Comment