Advertisement
bigyan

sudokuCheck

May 10th, 2011
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. /*
  2.     This is a sudoku board checker program that I wrote after seeing the question
  3.     being asked at a Google interview somewhere.
  4.    
  5.     Date: 110510, Tue 10 May 2011 10:11:32 AM IST
  6. */
  7.  
  8. // to check that the elements are indeed <=9 and >=1
  9. int check1to9(int board[9][9]) {
  10.     int i, j;
  11.     for (i=0; i<9; ++i)
  12.         for (j=0; j<9; ++j)
  13.             if (board[i][j]<=0 || board[i][j]>9)
  14.                 return 0;
  15.     return 1;
  16. }
  17.  
  18. // cheeck each row and each column for presence of all 9 digits
  19. int checkRowColumn(int board[9][9]) {
  20.     int i, j;
  21.     int testRow[10], testCol[10];
  22.     int sumRow, sumCol;
  23.    
  24.     for (i=0; i<9; ++i) {
  25.         for (j=1; j<=9; ++j)
  26.             testRow[j] = testCol[j] = 0;
  27.         for (j=0; j<9; ++j) {
  28.             testRow[board[i][j]]=1;
  29.             testCol[board[j][i]]=1;
  30.         }
  31.         sumRow = sumCol = 0;
  32.         for (j=1; j<=9; ++j) {
  33.             sumRow += testRow[j];
  34.             sumCol += testCol[j];
  35.         }
  36.         if (sumRow!=9 || sumCol!=9)
  37.             return 0;
  38.     }
  39.     return 1;
  40. }
  41.  
  42. // check each box for presence of all 9 digits
  43. int checkBox(int board[9][9]) {
  44.     int i, j, sum;
  45.     int test[10];
  46.     for (i=0; i<9; i+=3)
  47.         for (j=0; j<9; j+=3) {
  48.             for (k=1; k<=9; ++k)
  49.                 test[k]=0;
  50.             for (r=i; r<i+3; ++r)
  51.                 for (c=j; c<j+3; ++c)
  52.                     test[board[r][c]]=1;
  53.             sum=0;
  54.             for (k=1; k<=9; ++k)
  55.                 sum += test[k];
  56.             if (sum!=9)
  57.                 return 0;
  58.         }
  59.     return 1;
  60. }
  61.  
  62. // final function
  63. int sudokuCheck (int board[9][9]) {
  64.     if (check1to9(board) && checkRowColumn(board) && checkBox(board))
  65.         return 1;
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement