Advertisement
yimengael

Number of Path in A Matrix 2

Mar 19th, 2022
1,076
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1.  
  2.     static Integer number_of_paths(ArrayList<ArrayList<Integer>> matrix) {
  3.         int nr = matrix.size();
  4.         int nc = matrix.get(0).size();
  5.         int modulo = 1000000007;
  6.        
  7.         //edge case
  8.         if (matrix.get(0).get(0) == 0 || matrix.get(nr-1).get(nc-1) == 0) {
  9.             return 0;
  10.         }
  11.        
  12.         int[][] now = new int[nr][nc];
  13.        
  14.         //if we can reach cell (0,0) then number of ways to reach it is 1
  15.         now[0][0] = 1;
  16.        
  17.         //Filling the cells in the first row.
  18.         for (int c = 1; c < nc; c++){
  19.             if (matrix.get(0).get(c) == 1 && now[0][c-1] == 1) {
  20.                 now[0][c] = 1;
  21.             }
  22.         }
  23.        
  24.         //Filling the cells in the frist column
  25.         for (int r = 1; r < nr; r++) {
  26.             if (matrix.get(r).get(0) == 1 && now[r-1][0] == 1) {
  27.                 now[r][0] = 1;
  28.             }
  29.         }
  30.        
  31.         /*number of ways to reach
  32.         cell(i,j) = number of ways to reach cell(i-1,j) + number of ways to reach cell (i,j-1)*/
  33.         for (int r = 1; r < nr; r++) {
  34.             for (int c = 1; c < nc; c++) {
  35.                 now[r][c] = (now[r-1][c] % modulo + now[r][c-1] % modulo) % modulo;
  36.             }
  37.         }
  38.        
  39.         return now[nr-1][nc-1] % modulo;
  40.     }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement