Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
將此提示複製到我們的開發者 Console 中親自試用!
| 內容 | |
|---|---|
| System | 您的任務是根據提供的自然語言請求建立 Python 函式。請求將描述函式的預期功能,包括輸入參數和預期回傳值。請根據給定的規格實作函式,確保它們能處理邊界情況、執行必要的驗證,並遵循 Python 程式設計的最佳實踐。請在程式碼中包含適當的註解,以解釋邏輯並協助其他開發者理解實作方式。 |
| User | 我想要一個能解決數獨謎題的函式。該函式應接受一個 9x9 的數獨網格作為輸入,其中空白格以值 0 表示。該函式應使用回溯演算法來解決謎題,並回傳已解決的網格。如果謎題無法解決,應回傳 None。該函式還應驗證輸入網格,以確保它是一個有效的數獨謎題。 |
def solve_sudoku(grid):
def is_valid(row, col, num):
# Check if the number is valid in the current row and column
for i in range(9):
if grid[row][i] == num or grid[i][col] == num:
return False
# Check if the number is valid in the current 3x3 subgrid
start_row, start_col = (row // 3) * 3, (col // 3) * 3
for i in range(3):
for j in range(3):
if grid[start_row + i][start_col + j] == num:
return False
return True
def backtrack(row, col):
# If we have filled all cells, the puzzle is solved
if row == 9:
return True
# Move to the next row if we have reached the end of the current row
if col == 9:
return backtrack(row + 1, 0)
# If the current cell is already filled, move to the next cell
if grid[row][col] != 0:
return backtrack(row, col + 1)
# Try filling the current cell with numbers from 1 to 9
for num in range(1, 10):
if is_valid(row, col, num):
grid[row][col] = num
if backtrack(row, col + 1):
return True
grid[row][col] = 0
# If no valid number is found, backtrack
return False
# Validate the input grid
if not all(len(row) == 9 and all(0 <= cell <= 9 for cell in row) for row in grid):
return None
# Start the backtracking algorithm
if backtrack(0, 0):
return grid
else:
return None
Was this page helpful?