swiftUI 生成随机数独内容并且空出20个格子 全部代码
以下是使用SwiftUI生成随机数独内容并且空出20个格子的完整代码:
import SwiftUI
struct ContentView: View {
@State var sudokuGrid: [[Int]] = []
var body: some View {
VStack {
ForEach(0..<9) { row in
HStack {
ForEach(0..<9) { col in
Text("\(sudokuGrid[row][col])")
.font(.title)
.frame(width: 30, height: 30)
.background(Color.white)
.border(Color.black, width: 1)
}
}
}
}
.onAppear {
generateSudokuGrid()
removeNumbers()
}
}
func generateSudokuGrid() {
sudokuGrid = Array(repeating: Array(repeating: 0, count: 9), count: 9)
// 生成完整的数独内容
solveSudoku(&sudokuGrid)
}
func solveSudoku(_ grid: inout [[Int]]) -> Bool {
for row in 0..<9 {
for col in 0..<9 {
if grid[row][col] == 0 {
for num in 1...9 {
if isValid(grid, row, col, num) {
grid[row][col] = num
if solveSudoku(&grid) {
return true
}
grid[row][col] = 0
}
}
return false
}
}
}
return true
}
func isValid(_ grid: [[Int]], _ row: Int, _ col: Int, _ num: Int) -> Bool {
// 检查行是否有重复数字
for i in 0..<9 {
if grid[row][i] == num {
return false
}
}
// 检查列是否有重复数字
for i in 0..<9 {
if grid[i][col] == num {
return false
}
}
// 检查3x3方格内是否有重复数字
let startRow = (row / 3) * 3
let startCol = (col / 3) * 3
for i in startRow..<startRow+3 {
for j in startCol..<startCol+3 {
if grid[i][j] == num {
return false
}
}
}
return true
}
func removeNumbers() {
var count = 0
while count < 20 {
let row = Int.random(in: 0..<9)
let col = Int.random(in: 0..<9)
if sudokuGrid[row][col] != 0 {
sudokuGrid[row][col] = 0
count += 1
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
这段代码定义了一个名为ContentView
的视图,其中的sudokuGrid
变量用于存储数独内容。视图的正文部分使用了嵌套的ForEach
循环来创建数独格子,并通过绑定sudokuGrid
中的值来显示数字。
在视图的onAppear
回调中,我们调用generateSudokuGrid
函数来生成数独内容,并调用removeNumbers
函数来随机删除20个数字。
generateSudokuGrid
函数使用递归的方式解决数独问题,将结果保存到sudokuGrid
中。
removeNumbers
函数使用随机数生成器来随机选择20个位置,并将这些位置对应的数字设置为0,以实现空出20个格子的效果。
最后,我们在ContentView_Previews
中预览了ContentView
视图。
希望对你有帮助
原文地址: https://cveoy.top/t/topic/iaKU 著作权归作者所有。请勿转载和采集!