Skip to content

Instantly share code, notes, and snippets.

@madhur
Created May 25, 2019 15:05
Show Gist options
  • Select an option

  • Save madhur/2279995f1d3b25be62e174cb3fbd8bf8 to your computer and use it in GitHub Desktop.

Select an option

Save madhur/2279995f1d3b25be62e174cb3fbd8bf8 to your computer and use it in GitHub Desktop.
Print matrix paths
// java.util.* and java.util.streams.* have been imported for this problem.
// You don't need any other imports.
public ArrayList<String> printPaths(char[][] board){
StringBuilder sb = new StringBuilder();
ArrayList<String> paths = new ArrayList<String>();
if(board.length ==0 || board[0].length==0) return paths;
helper(board, sb, 0, 0, paths);
System.out.println(sb.toString());
return paths;
}
private void helper(char[][] board, StringBuilder sb, int x, int y, ArrayList<String> paths) {
int rows = board.length;
int cols = board[0].length;
sb.append(board[x][y]);
if(x==rows-1 && y==cols-1) {
paths.add(sb.toString());
sb.deleteCharAt(sb.length()-1); // Un-Mark
return;
}
if (x<rows-1)
helper(board, sb, x+1, y, paths);
if (y<cols-1)
helper(board, sb, x, y+1, paths);
sb.deleteCharAt(sb.length()-1); // Un-Mark
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment