Valid Sudoku Problem on InterviewBit Solution

0
240

Valid Sudoku: Understanding the Sudoku Puzzle’s Rules and Validation

A Sudoku puzzle is a popular logic-based number placement game played on a 9×9 grid. The objective is to fill in the grid’s cells with digits from 1 to 9, such that each column, each row, and each of the nine 3×3 subgrids (often referred to as “regions” or “boxes”) contains all the digits from 1 to 9 without repetition. A valid Sudoku puzzle adheres to specific rules and can be solved using logical deduction.(Valid Sudoku Problem)

Rules of a Valid Sudoku Puzzle:

  1. Row Rule: Each row must contain all digits from 1 to 9, without repetition. In other words, no digit can appear more than once in a row.
  2. Column Rule: Each column must also contain all digits from 1 to 9, without repetition. Like rows, no digit can appear more than once in a column.
  3. Box Rule: Each 3×3 subgrid must contain all digits from 1 to 9, without repetition. This rule applies to each of the nine individual boxes in the larger 9×9 grid.

A Sudoku puzzle starts with some cells already filled with numbers, and the challenge is to logically deduce the correct numbers to fill the remaining empty cells while adhering to the rules above.

Validating a Sudoku Puzzle:

To determine whether a Sudoku puzzle is valid, you need to ensure that the numbers filled in the grid follow the row, column, and box rules. Here’s how you can validate a Sudoku puzzle:

  1. Row and Column Validation: Check each row and column to verify that no digit is repeated. Go through every row and column and ensure that the digits 1 through 9 appear only once in each row and column.
  2. Box Validation: For each of the nine 3×3 boxes, ensure that the digits 1 through 9 appear only once. You can do this by dividing the grid into these boxes and verifying the digits in each box.

If all three validation checks pass without any repetition or missing digits, then the Sudoku puzzle is considered valid.

Solving a Sudoku Puzzle:

Solving a Sudoku puzzle involves using logical deduction to fill in the missing numbers. You start by identifying cells where only one number can fit based on the numbers already present in the same row, column, and box. As you fill in more numbers, you create new opportunities for deduction. Solving Sudoku puzzles requires a combination of pattern recognition, elimination, and trial-and-error techniques.

In conclusion, a valid Sudoku puzzle follows strict rules that ensure each row, column, and box contains the numbers 1 through 9 without repetition. Validating a Sudoku puzzle involves checking for adherence to these rules, while solving a Sudoku puzzle requires logical deduction and careful analysis to fill in the missing numbers.

let’s break down the explanation of a program to check if a Sudoku puzzle is valid using both Java and Python.

Java Implementation:

public class SudokuValidator {

    public static boolean isValidSudoku(char[][] board) {
        for (int i = 0; i < 9; i++) {
            if (!isValidRow(board, i) || !isValidColumn(board, i) || !isValidBox(board, i)) {
                return false;
            }
        }
        return true;
    }

    private static boolean isValidRow(char[][] board, int row) {
        boolean[] seen = new boolean[9];
        for (int i = 0; i < 9; i++) {
            char num = board[row][i];
            if (num != '.') {
                int digit = num - '1';
                if (seen[digit]) {
                    return false;
                }
                seen[digit] = true;
            }
        }
        return true;
    }

    private static boolean isValidColumn(char[][] board, int col) {
        boolean[] seen = new boolean[9];
        for (int i = 0; i < 9; i++) {
            char num = board[i][col];
            if (num != '.') {
                int digit = num - '1';
                if (seen[digit]) {
                    return false;
                }
                seen[digit] = true;
            }
        }
        return true;
    }

    private static boolean isValidBox(char[][] board, int box) {
        boolean[] seen = new boolean[9];
        int startRow = (box / 3) * 3;
        int startCol = (box % 3) * 3;
        for (int i = startRow; i < startRow + 3; i++) {
            for (int j = startCol; j < startCol + 3; j++) {
                char num = board[i][j];
                if (num != '.') {
                    int digit = num - '1';
                    if (seen[digit]) {
                        return false;
                    }
                    seen[digit] = true;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        // Create and initialize the Sudoku board
        char[][] sudokuBoard = {
            {'5', '3', '.', '.', '7', '.', '.', '.', '.'},
            {'6', '.', '.', '1', '9', '5', '.', '.', '.'},
            {'.', '9', '8', '.', '.', '.', '.', '6', '.'},
            // ... (fill in the rest of the Sudoku puzzle)
        };

        boolean isValid = isValidSudoku(sudokuBoard);
        System.out.println("Is the Sudoku puzzle valid? " + isValid);
    }
}

Python Implementation:

def is_valid_sudoku(board):
    for i in range(9):
        if not is_valid_row(board, i) or not is_valid_column(board, i) or not is_valid_box(board, i):
            return False
    return True

def is_valid_row(board, row):
    seen = [False] * 9
    for i in range(9):
        num = board[row][i]
        if num != '.':
            digit = int(num) - 1
            if seen[digit]:
                return False
            seen[digit] = True
    return True

def is_valid_column(board, col):
    seen = [False] * 9
    for i in range(9):
        num = board[i][col]
        if num != '.':
            digit = int(num) - 1
            if seen[digit]:
                return False
            seen[digit] = True
    return True

def is_valid_box(board, box):
    seen = [False] * 9
    start_row = (box // 3) * 3
    start_col = (box % 3) * 3
    for i in range(start_row, start_row + 3):
        for j in range(start_col, start_col + 3):
            num = board[i][j]
            if num != '.':
                digit = int(num) - 1
                if seen[digit]:
                    return False
                seen[digit] = True
    return True

# Create and initialize the Sudoku board
sudoku_board = [
    ['5', '3', '.', '.', '7', '.', '.', '.', '.'],
    ['6', '.', '.', '1', '9', '5', '.', '.', '.'],
    ['.', '9', '8', '.', '.', '.', '.', '6', '.'],
    # ... (fill in the rest of the Sudoku puzzle)
]

is_valid = is_valid_sudoku(sudoku_board)
print("Is the Sudoku puzzle valid?", is_valid)

Both implementations use similar logic to check the validity of the Sudoku puzzle based on the row, column, and box rules. The Java code utilizes classes and methods, while the Python code uses functions to achieve the same result.(Valid Sudoku Problem)

Thank You!

LEAVE A REPLY

Please enter your comment!
Please enter your name here