Created
May 25, 2019 15:05
-
-
Save madhur/2279995f1d3b25be62e174cb3fbd8bf8 to your computer and use it in GitHub Desktop.
Print matrix paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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