Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sudoku;
- public class Sudoku {
- public static void main(String[] args) {
- int[][] s1 = {
- {1, 3, 2, 5, 7, 9, 4, 6, 8},
- {4, 9, 8, 2, 6, 1, 3, 7, 5},
- {7, 5, 6, 3, 8, 4, 2, 1, 9},
- {6, 4, 3, 1, 5, 8, 7, 9, 2},
- {5, 2, 1, 7, 9, 3, 8, 4, 6},
- {9, 8, 7, 4, 2, 6, 5, 3, 1},
- {2, 1, 4, 9, 3, 5, 6, 8, 7},
- {3, 6, 5, 8, 1, 7, 9, 2, 4},
- {8, 7, 9, 6, 4, 2, 1, 5, 3}
- };
- System.out.println(verificaSudoku(s1));
- // Coluna 8, valor 3 repetido
- int[][] s2 = {
- {1, 3, 2, 5, 7, 9, 4, 6, 8},
- {4, 9, 8, 2, 6, 1, 3, 7, 5},
- {7, 5, 6, 3, 8, 4, 2, 1, 9},
- {6, 4, 3, 1, 5, 8, 7, 9, 2},
- {5, 2, 1, 7, 9, 3, 8, 4, 6},
- {9, 8, 7, 4, 2, 6, 5, 3, 1},
- {2, 1, 4, 9, 3, 5, 6, 8, 7},
- {3, 6, 5, 8, 1, 7, 9, 2, 4},
- {8, 7, 9, 6, 4, 2, 1, 3, 5}
- };
- System.out.println(verificaSudoku(s2));
- // Bloco 1, valor 4 repetido
- // Valor 0 na linha 4 para não falhar no teste de linha e coluna
- int[][] s3 = {
- {1, 3, 2, 5, 7, 9, 4, 6, 8},
- {4, 9, 8, 2, 6, 1, 3, 7, 5},
- {7, 4, 6, 3, 8, 0, 2, 1, 9},
- {6, 0, 3, 1, 5, 8, 7, 9, 2},
- {5, 2, 1, 7, 9, 3, 8, 4, 6},
- {9, 8, 7, 4, 2, 6, 5, 3, 1},
- {2, 1, 4, 9, 3, 5, 6, 8, 7},
- {3, 6, 5, 8, 1, 7, 9, 2, 4},
- {8, 7, 9, 6, 4, 2, 1, 5, 3}
- };
- System.out.println(verificaSudoku(s3));
- }
- private static boolean verificaSudoku(int[][] m){
- return verificaHorizontais(m) && veirifcaVerticais(m) && verificaBlocos(m);
- }
- private static boolean verificaHorizontais(int[][] m){
- for(int[] l : m)
- if(!verificaVetor(l))
- return false;
- return true;
- }
- private static boolean veirifcaVerticais(int[][] m){
- int[] l = new int[9];
- for(int j = 0; j < m[0].length; j++){
- for(int i = 0; i < m.length; i++)
- l[i] = m[i][j];
- if(!verificaVetor(l))
- return false;
- }
- return true;
- }
- private static boolean verificaBlocos(int[][] m){
- int[] l = new int[9];
- for(int j = 0; j < 3; j++)
- for(int i = 0; i < 3; i++){
- for(int z = 0; z < 3; z++)
- System.arraycopy(m[z+i*3], j*3, l, z*3, 3);
- if(!verificaVetor(l))
- return false;
- }
- return true;
- }
- private static boolean verificaVetor(int[] v){
- for(int i = 0; i < v.length; i++)
- for(int j = i + 1; j < v.length; j++)
- if(v[i] == v[j])
- return false;
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment