Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This is a sudoku board checker program that I wrote after seeing the question
- being asked at a Google interview somewhere.
- Date: 110510, Tue 10 May 2011 10:11:32 AM IST
- */
- // to check that the elements are indeed <=9 and >=1
- int check1to9(int board[9][9]) {
- int i, j;
- for (i=0; i<9; ++i)
- for (j=0; j<9; ++j)
- if (board[i][j]<=0 || board[i][j]>9)
- return 0;
- return 1;
- }
- // cheeck each row and each column for presence of all 9 digits
- int checkRowColumn(int board[9][9]) {
- int i, j;
- int testRow[10], testCol[10];
- int sumRow, sumCol;
- for (i=0; i<9; ++i) {
- for (j=1; j<=9; ++j)
- testRow[j] = testCol[j] = 0;
- for (j=0; j<9; ++j) {
- testRow[board[i][j]]=1;
- testCol[board[j][i]]=1;
- }
- sumRow = sumCol = 0;
- for (j=1; j<=9; ++j) {
- sumRow += testRow[j];
- sumCol += testCol[j];
- }
- if (sumRow!=9 || sumCol!=9)
- return 0;
- }
- return 1;
- }
- // check each box for presence of all 9 digits
- int checkBox(int board[9][9]) {
- int i, j, sum;
- int test[10];
- for (i=0; i<9; i+=3)
- for (j=0; j<9; j+=3) {
- for (k=1; k<=9; ++k)
- test[k]=0;
- for (r=i; r<i+3; ++r)
- for (c=j; c<j+3; ++c)
- test[board[r][c]]=1;
- sum=0;
- for (k=1; k<=9; ++k)
- sum += test[k];
- if (sum!=9)
- return 0;
- }
- return 1;
- }
- // final function
- int sudokuCheck (int board[9][9]) {
- if (check1to9(board) && checkRowColumn(board) && checkBox(board))
- return 1;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement