24h購物| | PChome| 登入
2009-10-02 22:27:23| 人氣1,387| 回應1 | 上一篇 | 下一篇

ACM 989 989 - Su Doku

推薦 0 收藏 0 轉貼0 訂閱站台

作法 : DFS

對每個未填的格子做1~9的猜測,並在搜尋途中把不可能剪枝

需要檢查9宮格 以及橫 直

/**********************************************************/

#include<stdio.h>
#include<stdlib.h>
int n,map[10][10]={0};
int top,queue[100][2]={0};
int check(int x,int y,int num)
{
  int a,b;
 
  for(a=0;a<n*n;a++)
     if(map[x][a]==num&&a!=y) return 0;
  for(a=0;a<n*n;a++)
     if(map[a][y]==num&&a!=x) return 0;
  int xx=x/n,yy=y/n;
  xx*=n;
  yy*=n;
 
  for(a=0;a<n;a++)
     for(b=0;b<n;b++)
        if(map[xx+a][yy+b]==num&&(xx+a!=x&&yy+b!=y)) return 0;
  return 1;
}
int find=0;
void DFS(int now)
{
   int a,b;
   if(find==1) return;
  if(now==top)
       {
         find=1;
         for(a=0;a<n*n;a++)
            {
               for(b=0;b<n*n;b++)
                  printf("%d ",map[a][b]);
                  printf("\n");
            }
            return;
       }
 
  for(a=1;a<=n*n;a++)
     if(check(queue[now][0],queue[now][1],a)==1)
       {
         map[queue[now][0]][queue[now][1]]=a;
         DFS(now+1);
         map[queue[now][0]][queue[now][1]]=0;
       }
}
main()
{
 while(scanf("%d",&n)==1)
     {
       int a,b,c;
       top=0;
       int no=0;
       for(a=0;a<n*n;a++)
          for(b=0;b<n*n;b++)
             {
              scanf("%d",&map[a][b]);
              if(map[a][b]==0)
                 {
                 queue[top][0]=a;
                 queue[top][1]=b;
                 top++;
                 }
             }
        for(a=0;a<n*n;a++)
           for(b=0;b<n*n;b++)
              if(map[a][b]!=0)
                    if(check(a,b,map[a][b])==0) no=1;
        find=0;
        if(no==0)
          DFS(0);
        if(find==0) printf("NO SOLUTION\n");
     }
 return 0;
}

台長: 來源不明
人氣(1,387) | 回應(1)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 數位資訊(科技、網路、通訊、家電) | 個人分類: ACM |
此分類下一篇:ACM 750 750 - 8 Queens Chess Problem
此分類上一篇:ACM 167 The Sultan's Successors

scbpz
夏天到了 真是热呀
2013-05-15 22:04:22
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文