fork download
  1. class GfG {
  2.  
  3. // this program takes in two 2D arrays as
  4. // input and compares them to find out the
  5. // minimum number of changes that needs to
  6. // be made to convert arr to ms.
  7. public static int findMinimumFromMS(int[][] arr,
  8. int[][] ms)
  9. {
  10. int count = 0;
  11. for (int i = 0; i < 3; i++) {
  12. for (int j = 0; j < 3; j++) {
  13. if (arr[i][j] != ms[i][j])
  14. count++;
  15. }
  16. }
  17. return count;
  18. }
  19.  
  20. public static int findMinimum(int[][] arr)
  21. {
  22. int[][][] ms = {
  23. { { 8, 1, 6 }, { 3, 5, 7 }, { 4, 9, 2 } },
  24. { { 6, 1, 8 }, { 7, 5, 3 }, { 2, 9, 4 } },
  25. { { 4, 9, 2 }, { 3, 5, 7 }, { 8, 1, 6 } },
  26. { { 2, 9, 4 }, { 7, 5, 3 }, { 6, 1, 8 } },
  27. { { 8, 3, 4 }, { 1, 5, 9 }, { 6, 7, 2 } },
  28. { { 4, 3, 8 }, { 9, 5, 1 }, { 2, 7, 6 } },
  29. { { 6, 7, 2 }, { 1, 5, 9 }, { 8, 3, 4 } },
  30. { { 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 } },
  31. };
  32.  
  33. // If all the elements need to be changed,
  34. // there would be 9 changes, so we take the
  35. // max as 9
  36. int min = 9;
  37. for (int i = 0; i < 8; i++) {
  38. int x = findMinimumFromMS(arr, ms[i]);
  39. if (x < min)
  40. min = x;
  41. }
  42. return min;
  43. }
  44.  
  45. public static void main(String[] args)
  46. {
  47. int[][] arr = { { 4,8,2 }, { 4,5,7},
  48. { 6,1,6 } };
  49. System.out.println(findMinimum(arr));
  50. }
  51. }
Success #stdin #stdout 0.07s 32552KB
stdin
Standard input is empty
stdout
3