2011年6月16日 星期四

Online Judge-數獨檢查

題目出處:zero judge

problem:輸入9*9之矩陣 數字1~9,判斷是否符合數獨 yes or no



ex:
in:
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8

1 9 3 2 6 5 4 7 8
7 8 2 3 1 4 9 5 6
4 5 6 9 7 8 1 3 2
2 3 4 8 5 1 6 9 7
9 6 5 4 3 7 2 8 1
8 7 1 6 9 2 3 4 5
3 1 9 5 8 6 7 2 4
5 2 7 1 4 3 8 6 9
6 4 8 7 2 9 5 1 3

out:
no
yes

code:
 1 #include<stdio.h>
 2 int check(int,int);
 3 int su[9][9];
 4 int main()
 5 {
 6         int i,j;
 7         while(scanf("%d %d %d %d %d %d %d %d %d",
 8                 &su[0][0],&su[0][1],&su[0][2],&su[0][3],
 9                 &su[0][4],&su[0][5],&su[0][6],&su[0][7],
10                 &su[0][8])!=EOF)
11         {
12                 for(i=1;i<9;i++)
13                         for(j=0;j<9;j++)
14                                 scanf("%d",&su[i][j]);
15                 //check row and column
16                 for(i=0;i<9;i++)
17                 {
18                         int chr[9]={0},chc[9]={0};
19                         for(j=0;j<9;j++)
20                         {
21                                 chr[su[i][j]-1]++;
22                                 chc[su[j][i]-1]++;
23 
24                                 if(chr[su[i][j]-1]>1||chc[su[j][i]-1]>1)
25                                 {
26                                         puts("no");
27                                         break;
28                                 }
29                         }
30                         if(j<9)break;
31                 }
32                 if(i<9)continue;
33                 //check square
34                 for(i=0;i<7;i+=3)
35                 {
36                         for(j=0;j<7;j+=3)
37                         {
38                                 if(check(i,j)==0){puts("no");break;}
39                         }
40                         if(j<7)break;
41                 }
42                 if(i>7)puts("yes");
43         }
44         return 0;
45 }
46 
47 int check(int r,int c)
48 {
49         int i,j,ch[9]={0};
50         for(i=r;i<r+3;i++)
51                 for(j=c;j<c+3;j++)
52                         ch[su[i][j]-1]++;
53         for(i=0;i<9;i++)
54                 if(ch[i]>1)return 0;
55         return 1;
56 }

沒有留言:

張貼留言