Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.9 kB
13
Indexable
Never
module SudukuSolver #(
  parameter int NUM_ROWS = 9,
  parameter int NUM_COLS = 9
) (
  input logic clk,
  input logic ready,
  input logic [NUM_ROWS-1:0][NUM_COLS-1:0] board,
  output logic valid
);

logic [NUM_ROWS-1:0] row_seen [NUM_ROWS-1:0];
logic [NUM_COLS-1:0] col_seen [NUM_COLS-1:0];
logic [3:0] box_seen [3-1:0][3-1:0];

always_ff @(posedge clk) begin
  if (ready) begin
    valid = 1'b1;

    // Check rows
    for (int i = 0; i < NUM_ROWS; i++) begin
      row_seen[i] = 0;
      for (int j = 0; j < NUM_COLS; j++) begin
        if (board[i][j] != ".") begin
          if (row_seen[i] & (1 << (board[i][j] - "1"))) begin
            valid = 1'b0;
            break;
          end else begin
            row_seen[i] |= (1 << (board[i][j] - "1"));
          end
        end
      end
    end

    // Check columns
    for (int j = 0; j < NUM_COLS; j++) begin
      col_seen[j] = 0;
      for (int i = 0; i < NUM_ROWS; i++) begin
        if (board[i][j] != ".") begin
          if (col_seen[j] & (1 << (board[i][j] - "1"))) begin
            valid = 1'b0;
            break;
          end else begin
            col_seen[j] |= (1 << (board[i][j] - "1"));
          end
        end
      end
    end

    // Check boxes
    for (int i = 0; i < 3; i++) begin
      for (int j = 0; j < 3; j++) begin
        box_seen[i][j] = 0;
        for (int k = 0; k < 3; k++) begin
          for (int l = 0; l < 3; l++) begin
            int row = (i * 3) + k;
            int col = (j * 3) + l;
            if (board[row][col] != ".") begin
              if (box_seen[i][j] & (1 << (board[row][col] - "1"))) begin
                valid = 1'b0;
                break;
              end else begin
                box_seen[i][j] |= (1 << (board[row][col] - "1"));
              end
            end
          end
        end
      end
    end
  end
end

endmodule
Leave a Comment