Print All Paths in a 2D Board
Posted tobeabetterpig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Print All Paths in a 2D Board相关的知识,希望对你有一定的参考价值。
Print All Paths in a 2D Board public class Solution { private int m; private int n; public void printAllPath(char[][] grid) { int count=0; m=grid.length; if(m==0) return 0; n=grid[0].length; dfs(grid,0,0,""); } public void dfs(char[][] grid,int i,int j,String s){ if(i>m||j>n) return; if(i==m&&j==n) print(s+grid[i][j]); dfs(grid,i,j+1,s+grid[i][j]+"->"); dfs(grid,i+1,j,s+grid[i][j]+"->"); } } follow up是如果board很大,怎么优化。答用stringbuilder public List<String> printAllPath(char[][] board){ List<String> res = new ArrayList<>(); StringBuilder sb = new StringBuilder(); dfs(board,res,sb,0,0); return res; } public void dfs(char[][] b, List<String> res, StringBuilder sb, int x, int y){ int len = sb.length(); sb.append(b[y][x]); if( x == b[0].length - 1 && y == b.length - 1){ String s = sb.toString(); res.add(s); } else{ if( x + 1 < b[0].length) dfs(b,res,sb,x+1,y); if( y + 1 < b.length ) dfs(b,res,sb,x,y+1); } sb.setLength(len); }
以上是关于Print All Paths in a 2D Board的主要内容,如果未能解决你的问题,请参考以下文章
Find all paths with min weights in an undirected graph
AtCoder Regular Contest 102D All Your Paths are Different Lengths 构造
[GeeksForGeeks] Print all nodes that don't have sibling in a binary tree.