c++遞歸解數(shù)獨方法示例
#include<iostream>
using namespace std;
void init();
void function(int m);
int canplace(int row,int col,int c);
void outputresult();
int a[9][9], maxm = 0;
int main()
{
init();
function(0);
return 0;
}
void init()
{
int i, j;
for(i = 0; i < 9; i++)
{
for(j = 0; j < 9; j++)
{
cin >> a[i][j];
}
}
}
void function(int m)
{
int i, j, row, col;
if (m >= 81)
{
outputresult();
}
else
{
row = m / 9;
col = m % 9;
if(a[row][col] != 0)
{
function(m+1);
}
for(i = 1; i <= 9; i++)
{
if(canplace(row,col,i) == 1)
{
a[row][col] = i;
function(m + 1);
a[row][col] = 0;
}
}
}
}
int canplace(int row,int col,int c)
{
int i, j;
int flag = 1;
for(i = 0; i < 9; i++ )
{
if(a[row][i] == c || a[i][col] == c)
{
flag = 0;
break;
}
}
if(flag != 0)
{
for(i = (row / 3) * 3; i < (row / 3) * 3 + 3; i++)
{
for(j = (col / 3) * 3; j < (col / 3) * 3 + 3; j++)
{
if(a[i][j] == c)
{
flag = 0;
break;
}
}
if(flag == 0)
{
break;
}
}
}
return flag;
}
void outputresult()
{
int i, j;
for(i = 0; i < 9; i++)
{
if(i % 3 == 0)
{
cout << endl;
}
for(j = 0; j < 9; j++)
{
if(j % 3 == 0)
{
cout << " ";
}
cout << a[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
相關(guān)文章
詳解C++ 多態(tài)的兩種形式(靜態(tài)、動態(tài))
這篇文章主要介紹了C++ 多態(tài)的兩種形式,幫助大家更好的理解和學(xué)習(xí)c++,感興趣的朋友可以了解下2020-08-08c++基礎(chǔ)語法:構(gòu)造函數(shù)與析構(gòu)函數(shù)
構(gòu)造函數(shù)用來構(gòu)造一個對象,主要完成一些初始化工作,如果類中不提供構(gòu)造函數(shù),編譯器會默認的提供一個默認構(gòu)造函數(shù)(參數(shù)為空的構(gòu)造函數(shù)就是默認構(gòu)造函數(shù)) ;析構(gòu)函數(shù)是隱式調(diào)用的,delete對象時候會自動調(diào)用完成對象的清理工作2013-09-09C++實現(xiàn)LeetCode(170.兩數(shù)之和之三 - 數(shù)據(jù)結(jié)構(gòu)設(shè)計)
這篇文章主要介紹了C++實現(xiàn)LeetCode(170.兩數(shù)之和之三 - 數(shù)據(jù)結(jié)構(gòu)設(shè)計),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08詳解C++編程中用數(shù)組名作函數(shù)參數(shù)的方法
這篇文章主要介紹了詳解C++編程中用數(shù)組名作函數(shù)參數(shù)的方法,是C++入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09