数独 数独是一种逻辑游戏,玩家需要根据9x9盘面的已知数字,推理出剩余所有空格的数字,并满足每一行、每一列和每个粗线宫(3x3)内均含1~9,不重复。 MATLAB中有关函数 M = dlmread(filename,delimiter) 使用指定的分隔符,将该文件的数据读取到矩阵M中,并将重复的分隔符视为单个的分隔符 disp(x) 显示变量x的值,而不打印变量名称 代码实现 文件目录 check3_by_3.m
check_cell.m
check_col.m
check_row.m
data.txt
shudu.m
slove.m
check3_by_3.m 1 function res = check3_by_3(matrix,i,j,num) 2 %检查(i,j)能否放num 3 res = true; 4 block_row = floor((i - 1) / 3) + 1; 5 block_col = floor((j - 1) / 3) + 1; 6 7 block_row_to = block_row * 3; 8 block_row_from = block_row_to - 2; 9 block_col_to = block_col * 3; 10 block_col_from = block_col_to - 2; 11 12 for row = block_row_from : block_row_to 13 for col = block_col_from : block_col_to 14 if matrix(row,col) == num 15 res = false; 16 break; 17 end 18 end 19 end 20 end check_cell.m 1 function res = check_cell(matrix,i,j,num) 2 %按九宫格检查(i,j)能否放num 3 if check_row(matrix,i,j,num) && check_col(matrix,i,j,num) && check3_by_3(matrix,i,j,num) 4 res = true; 5 else 6 res = false; 7 end 8 end check_col.m 1 function res = check_col(matrix,i,j,num) 2 %按列检查(i,j)能否放num 3 res = true; 4 for row = 1 : 9 5 if matrix(row,j) == num 6 res = false; 7 break; 8 end 9 end 10 end check_row.m 1 function res = check_row(matrix,i,j,num) 2 %按行检查(i,j)能否放num 3 res = true; 4 for col = 1 : 9 5 if matrix(i,col) == num 6 res = false; 7 break; 8 end 9 end 10 end data.txt (想要破解的数独矩阵) 5 3 0 0 7 0 0 0 0 6 0 0 1 9 5 0 0 0 0 9 8 0 0 0 0 6 0 8 0 0 0 6 0 0 0 3 4 0 0 8 0 3 0 0 1 7 0 0 0 2 0 0 0 6 0 6 0 0 0 0 2 8 0 0 0 0 4 1 9 0 0 5 0 0 0 0 8 0 0 7 9 shudu.m (主程序) 1 matrix = dlmread('data3.txt',''); 2 disp(matrix); 3 solve(matrix,1); slove.m 1 function solve(matrix,id) 2 %按编号逐一填充,递归 3 if id > 81 4 disp(matrix); 5 else 6 row = floor((id - 1) / 9) + 1; 7 col = mod((id - 1),9) + 1; 8 9 if matrix(row,col) ~= 0 10 solve(matrix,id + 1); 11 else 12 for i = 1 : 9 13 if check_cell(matrix,row,col,i) == true 14 matrix(row,col) = i; 15 solve(matrix,id + 1); 16 end 17 end 18 end 19 end 20 end 效果图
参考链接:https://youtu.be/La57P8wNnLA
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论