[LintCode] 1840. Matrix restoration
There is a matrix beforebefore with nn rows and mm columns. For each element in before before[i][j]before[i][j], we will use the following algorithm to convert it to after [i] [j]after[i][j]. Given the afterafter matrix, please restore the original matrix beforebefore.
s = 0
for i1: 0 -> i
for j1: 0 -> j
s = s + before[i1][j1]
after[i][j] = s
Example
Input: 2 2 [[1,3],[4,10]] Output: [[1,2],[3,4]] Explanation: before: 1 2 3 4 after: 1 3 4 10
public class Solution { /** * @param n: the row of the matrix * @param m: the column of the matrix * @param after: the matrix * @return: restore the matrix */ public int[][] matrixRestoration(int n, int m, int[][] after) { // write your code here // pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i- 1][j - 1] + grid[i][j] // grid[i][j] = pre[i][j] - pre[i - 1][j] - pre[i][j - 1] + pre[i- 1][j - 1] int[][] res = new int[after.length][after[0].length]; for(int i = 0; i < after.length; i++) { for (int j = 0; j < after[0].length; j++) { res[i][j] = after[i][j]; if (i > 0) { res[i][j] -= after[i - 1][j]; } if (j > 0) { res[i][j] -= after[i][j - 1]; } if (i > 0 && j > 0) { res[i][j] += after[i - 1][j - 1]; } } } return res; } }