Created
December 10, 2012 04:53
-
-
Save maccam912/4248442 to your computer and use it in GitHub Desktop.
Solution to HackerRank Olympics sudoku puzzle in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
#include<set> | |
#include<math.h> | |
using namespace std; | |
int getSector(int row, int col) { | |
return (row/3)*3+(col/3); | |
} | |
bool valid(int grid[9][9], int row, int col) { | |
for (int i = 0; i < 9; i++) { | |
if (grid[row][i] == grid[row][col] && i != col) return false; | |
if (grid[i][col] == grid[row][col] && i != row) return false; | |
} | |
for (int i = 0; i < 9; i++) { | |
for (int j = 0; j < 9; j++) { | |
if (getSector(row, col) == getSector(i, j) && row != i && col != j && grid[i][j] == grid[row][col]) return false; | |
} | |
} | |
return true; | |
} | |
/* Head ends here */ | |
void sudoku_solve(int grid[9][9],set<int> set) { | |
//your logic here | |
int forward = 1; | |
for (int idx = 0; idx < 81;) { | |
int row = floor(idx/9); | |
int col = fmod(idx,9); | |
if (set.count(idx)>0) { | |
idx += 1*forward; | |
} else { | |
grid[row][col]++; | |
if (grid[row][col] == 10) { | |
grid[row][col] = 0; | |
forward = -1; | |
idx--; | |
} | |
if (valid(grid, row, col)) { | |
forward = 1; | |
idx++; | |
} | |
} | |
} | |
for (int i = 0; i < 9; i++) { | |
for (int j = 0; j < 9; j++) { | |
cout << grid[i][j] << " "; | |
} | |
cout << endl; | |
} | |
} | |
/* Tail starts here */ | |
int main() { | |
int n, board[9][9]; | |
set<int> set; | |
cin >> n; | |
for(int i=0;i<n;i++) { | |
for(int j=0;j<9;j++) { | |
for(int k=0;k<9;k++) { | |
board[j][k] = 0; | |
cin >> board[j][k]; | |
if ( board[j][k] != 0 ) set.insert(j*9+k); | |
} | |
} | |
sudoku_solve(board,set); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment