Advertisement
yimengael

Number Of Paths In A Matrix

Mar 19th, 2022
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1.  
  2.     static Integer number_of_paths(ArrayList<ArrayList<Integer>> matrix) {
  3.         // We are going to use the Lazy manager approach to solve this problem.
  4.         // We start at the top left corner. the formula that describe this problem
  5.         // is given by the following :
  6.         // NOW(r, c) = NOW(r, c-1) + NOW(r-1, c). OR NOW(r, c) = NOW(r, c+1) + NOW(r+1, c)
  7.        
  8.         int nr = matrix.size();
  9.         int nc = matrix.get(0).size();
  10.         int modulo = 1000000007;
  11.        
  12.         long[][] now = new long[nr][nc];
  13.         now[0][0] = matrix.get(0).get(0);
  14.         for (int r = 0; r < nr; r++) {
  15.             for (int c = 0; c < nc; c++) {
  16.                 if (matrix.get(r).get(c) == 1 || (r == 0 && c == 0)) {
  17.                     continue;
  18.                 }
  19.                
  20.                 now[r][c] = (c >= 1 ? now[r][c - 1] : 0) % modulo +
  21.                             (r >= 1 ? now[r - 1][c] : 0) % modulo;
  22.             }
  23.         }
  24.        
  25.         return (int)now[nr-1][nc-1] % modulo;
  26.     }
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement