java的两个回溯算法编程题
发布日期:2021-05-07 02:40:15 浏览次数:23 分类:精选文章

本文共 1640 字,大约阅读时间需要 5 分钟。

此篇是在牛客网中剑指offer经过测试的两个关于回溯算法的编程题。并不都是自己写的,有见解大神的思路。

  1. 机器人的活动范围
  2. 矩阵中的路径
    1. 机器人的运动范围
    题目描述
    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
public class Solution {    public int movingCount(int threshold, int rows, int cols) {        boolean[] visited=new boolean[rows*cols];		return pathCount(visited,threshold,rows,cols,0,0);    }	private int pathCount(boolean[] visited, int threshold, int rows, int cols, int row, int col) {		if(row<0 || row>=rows || col<0 || col>=cols) {			return 0;		}		int n=row*cols+col;		if(visited[n] || !check(row,col,threshold)) {return 0;}		visited[n]=true;		return 1+pathCount(visited,threshold,rows,cols,row+1,col)				+pathCount(visited,threshold,rows,cols,row,col+1)				+pathCount(visited,threshold,rows,cols,row,col-1)				+pathCount(visited,threshold,rows,cols,row-1,col);	}	private boolean check(int i, int j, int threshold) {		int sum=0;		while(i!=0) {			int ys=i%10;			sum+=ys;			i=i/10;		}		while(j!=0) {			int ys=j%10;			sum+=ys;			j=j/10;		}		return sum<=threshold;	}}

2. 矩阵中的路径

题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

public class Solution {    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {		if(matrix==null || str==null) {			return false;		}		char [][] temp=new char[rows][cols];		int index=0;		//先将数组变为二维矩阵			for(int i=0;i
=0 && i
=0 && j
上一篇:java关于回溯算法的题1
下一篇:java语言解决负二进制的问题

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月05日 06时45分24秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章