public ArrayList<String> printPaths(char[][] board){
ArrayList<String> out = new ArrayList<>();
StringBuilder sb = new StringBuilder();
search(0,0,board,sb,out);
return out;
}
public void search(int i, int j, char[][] board, StringBuilder sb, ArrayList<String> out){
int rows = board.length;
int cols = board[0].length;
if(i > rows-1 || j > cols-1) return;
sb.append(board[i][j]); // Mark
if(i == rows-1 && j == cols-1){
out.add(sb.toString());
sb.deleteCharAt(sb.length()-1);
return;
}
search(i+1,j,board,sb,out); // Search Down
search(i,j+1,board,sb,out); // Search Right
sb.deleteCharAt(sb.length()-1); // Un-Mark
}
put returns between paragraphs for linebreak add two spaces at end► fix grammatical or spelling errors ► clarify meaning without changing it ► correct minor mistakes ► add related resources or links ► always respect the original author► fix grammatical or spelling errors ► clarify meaning without changing it ► correct minor mistakes ► add related resources or links ► always respect the original author
It is backtracking logic. See those instruction this way (comments added):
sb.append(board[i][j]); // Mark
if(i == rows-1 && j == cols-1){
out.add(sb.toString());
/*
Here, you reached the bottom-right element of the matrix.
You can no longer go down or right, so you perform a backtracking
by deleting the last element read.
*/
sb.deleteCharAt(sb.length()-1);
return;
}
search(i+1,j,board,sb,out); // Search Down
search(i,j+1,board,sb,out); // Search Right
/*
Here, you exhausted the elements on bottom and right
(because you just returned from the two search() calls). Perform a backtracking by
removing the last element (which is a dead end) before returning to the calling
recursion step:
*/
sb.deleteCharAt(sb.length()-1); // Un-Mark
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.