第一次一次过的hard题目,其实觉得难度应该算是中等难题。就是先找纵方向的中点,再找横方向的中点,思路类似一维的情况
public class Solution { public int minTotalDistance(int[][] grid) { int row = grid.length; if (row == 0) { return 0; } int col = grid[0].length; ArrayList<Integer> list_r = new ArrayList<Integer>(); ArrayList<Integer> list_c = new ArrayList<Integer>(); for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { if (grid[r][c] == 1) { list_r.add(r); } } } for (int c = 0; c < col; c++) { for (int r = 0; r < row; r++) { if (grid[r][c] == 1) { list_c.add(c); } } } int result_r = list_r.get(list_r.size() / 2); int result_c = list_c.get(list_c.size() / 2); int result = 0; for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { if (grid[r][c] == 1) { result += Math.abs(r - result_r) + Math.abs(c - result_c); } } } return result; } }