classSolution{publicintminOperations(int[][] grid,int x){int[] elements =newint[grid.length * grid[0].length];int index =0;// Move the elements from the gridfor(int i =0; i < grid.length;++i){for(int j =0; j < grid[0].length;++j){
elements[index]= grid[i][j];++index;}}// Sort it to find medianArrays.sort(elements);int median = elements[(elements.length -1)/2];int steps =0;// Count stepsfor(int i =0; i < elements.length;++i){// Skip the median itselfif(elements[i]== median)continue;// Found invalid valueif(Math.abs(elements[i]- median)% x !=0){return-1;}// Update steps
steps +=Math.abs(elements[i]- median)/ x;}return steps;}}