Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to find a path from top-left to bottom right of a grid with a minimum sum of all numbers along the path in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

// Minimum Path Sum
// We can only move down or right

public class Program {
    public static void Print2DList(List<List<Integer>> list2d) {
        for (List<Integer> list1d : list2d) {
            for (int val : list1d) {
                System.out.print(val + "  ");
            }
            System.out.println();
        }
    }

    public static int minPathSum(List<List<Integer>> grid) {
        int rows = grid.size();
        int cols = grid.get(rows - 1).size();
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int current = Integer.MAX_VALUE;
                if (i - 1 >= 0) {
                    current = Math.min(current, grid.get(i - 1).get(j));
                }
                if (j - 1 >= 0) {
                    current = Math.min(current, grid.get(i).get(j - 1));
                }
                if (current == Integer.MAX_VALUE) {
                    current = 0;
                }
                grid.get(i).set(j, grid.get(i).get(j) + current);
            }
        }
        
        Print2DList(grid);
        
        return grid.get(rows - 1).get(cols - 1);
    }

    public static void main(String[] args) {
        List<List<Integer>> grid = new ArrayList<>();
        
        grid.add(new ArrayList<>(List.of(1, 2, 3, 1, 4)));
        grid.add(new ArrayList<>(List.of(2, 1, 1, 3, 3)));
        grid.add(new ArrayList<>(List.of(3, 2, 2, 1, 5)));
        grid.add(new ArrayList<>(List.of(1, 2, 1, 4, 1)));
        
        // [0][0] (1) + [0][1] (2) + [1][1] (1) + [1][2] (1) + 
        // [2][2] (2) + [2][3] (1) + [3][3] (4) + [3][4] (1) = 
        // 1 + 2 + 1 + 1 + 2 + 1 + 4 + 1 = 13
        
        System.out.println(minPathSum(grid));
    }
}



/*
run:

1  3  6  7  11  
3  4  5  8  11  
6  6  7  8  13  
7  8  8  12  13  
13

*/

 



answered Mar 2, 2024 by avibootz
...