Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static Integer number_of_paths(ArrayList<ArrayList<Integer>> matrix) {
- int nr = matrix.size();
- int nc = matrix.get(0).size();
- int modulo = 1000000007;
- //edge case
- if (matrix.get(0).get(0) == 0 || matrix.get(nr-1).get(nc-1) == 0) {
- return 0;
- }
- int[][] now = new int[nr][nc];
- //if we can reach cell (0,0) then number of ways to reach it is 1
- now[0][0] = 1;
- //Filling the cells in the first row.
- for (int c = 1; c < nc; c++){
- if (matrix.get(0).get(c) == 1 && now[0][c-1] == 1) {
- now[0][c] = 1;
- }
- }
- //Filling the cells in the frist column
- for (int r = 1; r < nr; r++) {
- if (matrix.get(r).get(0) == 1 && now[r-1][0] == 1) {
- now[r][0] = 1;
- }
- }
- /*number of ways to reach
- cell(i,j) = number of ways to reach cell(i-1,j) + number of ways to reach cell (i,j-1)*/
- for (int r = 1; r < nr; r++) {
- for (int c = 1; c < nc; c++) {
- now[r][c] = (now[r-1][c] % modulo + now[r][c-1] % modulo) % modulo;
- }
- }
- return now[nr-1][nc-1] % modulo;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement