數獨(Sudoku)求解程式

來源:互聯網
上載者:User
/* 數獨完全求解程式 Ver 3.0 *//* coolypf *//* 2008-11-24 22:11 */#include <iostream>using namespace std;int matrix[9][9];  /*數獨矩陣*/int count = 0;     /*解的個數*/int check(int x, int y, bool mark[10]) /*檢測matrix[x][y]的取值範圍*/{  int i, j, c = 0;  for(i = 1; i <= 9; ++i)  {    mark[i] = true;  }  for(i = 0; i < 9; ++i)  {    mark[matrix[x][i]] = false;  }  for(i = 0; i < 9; ++i)  {    mark[matrix[i][y]] = false;  }  x = x / 3 * 3;  y = y / 3 * 3;  for(i = 0; i < 3; ++i)  {    for(j = 0; j < 3; ++j)    {      mark[matrix[x + i][y + j]] = false;    }  }  for(i = 1; i <= 9; ++i)  {    if(mark[i]) ++c;  }  return c;}void display()  /*輸出解*/{  int x, y;  cout << "Solution " << count << ":\n";  for(x = 0; x < 9; ++x)  {    for(y = 0; y < 9; ++y)    {      cout << matrix[x][y] <<' ';    }    cout << endl;  }}void sudoku()  /*求解數獨*/{  bool mark[10];  /*matrix中元素的取值範圍*/  int x, y, xm=-1, ym, min=10, c;  for(x = 0 ; x < 9; ++x)  /*檢測取值範圍最小的空格*/  {    for(y = 0; y < 9; ++y)    {      if(matrix[x][y]) continue;  /*非空格則跳過*/      c = check(x, y, mark);      if(c == 0) return;  /*不可解*/      if(c < min)      {        min = c;        xm = x;        ym = y;      }    }  }  if(xm == -1)  /*matrix填完*/  {    ++count;    display();    return;  }  check(xm, ym, mark);  for(x=1; x <= 9; ++x)  {    if(mark[x])    {      matrix[xm][ym] = x;  /*嘗試*/      sudoku();  /*遞迴*/    }  }  matrix[xm][ym]=0;  /*回溯*/}int main(){  int x, y;  for(x=0;x <9; ++x)  /*輸入數獨*/  {    for(y=0; y<9; ++y)    {      cin >> matrix[x][y];    }  }  sudoku();  /*求解數獨*/  cout << endl << count << " solution(s) in total.\n";  return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.