机器人的运动范围 (回溯法)

版权声明:be the one ~you will be the one~~ https://blog.csdn.net/Hqxcsdn/article/details/87895385

在这里插入图片描述
与上有一个矩阵路径问题相似,同样可以采用回溯法 ,从0开始试探,如果符合条件则会继续探查其周围的四个位置,每次走到位置,都会将其置为已经访问,当走不下去时,就会 返回上一层的位置,继续寻找剩下的周围的位置。

代码如下

/**
 * 
 */

/***
 * @author 18071
 * @Date 2019年2月23日
 * 功能: 机器人的运动范围:
 * 地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,
 * 它每次可以向左,向右,向上,向下移动一格,但不能进入行坐标和列坐标的位数之和大于k的格子。
 * 例如:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18;但它不能进入方格(35,38),
 * 因为3 + 5+3+8 = 19.请问该机器人最多能到达多少个格子?

 ***/
public class test {
	
	public static void main(String args[]) {
	int maxrow =100;
	int maxcolunm=100;
	
	boolean []isvisit = new boolean [10000];
	for(int i=0;i<10000;i++) {
		isvisit[i]=false;
		
	}
	
	int k=4;
	
	System.out.println(findthecount(k,0,0,maxrow,maxcolunm,isvisit));
		
	}
	
	public static int  findthecount(int k ,int row ,int colunm ,int maxrow,int maxcolunm, boolean isvisit[]) {
		int count =0;
		
		if(check( k , row , colunm , maxrow, maxcolunm,  isvisit)) {//能够进入 ,计算它的周围d的位置 
		
			//将该位置标记为 已经 进入 
			isvisit[row*maxcolunm+colunm] = true;
			
			count=1+findthecount(k , row-1 , colunm , maxrow, maxcolunm,  isvisit)+
					findthecount(k , row+1 , colunm , maxrow, maxcolunm,  isvisit)+
					findthecount(k , row , colunm+1 , maxrow, maxcolunm,  isvisit)+
					findthecount(k , row , colunm-1 , maxrow, maxcolunm,  isvisit);
			
			
		}
		
		
		
		return count;
		
	}
	
	public static boolean check(int k ,int row ,int colunm ,int maxrow,int maxcolunm, boolean isvisit[]) {
		
		boolean rua =false;
		System.out.println(row+"  " + maxrow +"   "+ colunm+"   " +maxcolunm);
            if(row>=0&& row<maxrow  &&colunm >=0&& colunm <maxcolunm && !isvisit[row*maxcolunm+colunm]) {//没被访问过哦
            	System.out.println(row/10+row%10+colunm/10+colunm%10);
			     if(k>=row/10+row%10+colunm/10+colunm%10)  {  
			    	rua=true;
			    	
			    	
			     }
            	
		       }
		
		
		return rua;
		
	}

}



结果如下

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Hqxcsdn/article/details/87895385