劍指Offer(java語言)--機器人的運動範圍(回溯法)

題目:

地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?

知識點:

回溯法

審題:一共到達多少格子,走過就算(開始算成最長路徑-_-);行座標和列座標的數位之和

思路:

1、定義boolean類型的二維數組作爲標記數組(走過,標爲true)

2、將第一個格子變爲true,進入遞歸循環:將k,二維數組,行數,列數,下標,返回的格子數(1:算上起點)傳入。

遞歸返回:走過的格子數

3、遞歸:判斷將要走的數組下標在範圍內,且將要走的格子爲false,將要走的格子的下標數位之和小於k-->可以走進該格子

(1)格子變爲true

(2)走過格子數+1

(3)繼續遞歸

4、計算格子的下標數位之和:%10,相加

答案:

import java.util.*;//自己
public class Solution {
    public int movingCount(int threshold, int rows, int cols)
    {
         if(threshold<0 || rows<=0 || cols<=0){return 0;}
        boolean[][] matrix = new boolean[rows][cols];
        matrix[0][0]=true;
        int r = check(threshold,rows,cols,0,0,matrix,1);
        
        return r;
    }
    public int check(int threshold, int rows, int cols,int i,int j,boolean[][] matrix,int r) {
    	if(i-1>=0 && matrix[i-1][j]==false && numSun(i-1,j)<=threshold) {
    		matrix[i-1][j]=true;
    		r++;
    		r = check(threshold,rows,cols,i-1,j,matrix,r);
    		
    	}
    	if(i+1<rows && matrix[i+1][j]==false && numSun(i+1,j)<=threshold) {
    		matrix[i+1][j]=true;
    		r++;
    		r = check(threshold,rows,cols,i+1,j,matrix,r);
    		
    	}
    	if(j-1>=0 && matrix[i][j-1]==false && numSun(i,j-1)<=threshold) {
    		matrix[i][j-1]=true;
    		r++;
    		r = check(threshold,rows,cols,i,j-1,matrix,r);
    		
    	}
    	if(j+1<cols && matrix[i][j+1]==false && numSun(i,j+1)<=threshold) {
    		matrix[i][j+1]=true;
    		r++;
    		r = check(threshold,rows,cols,i,j+1,matrix,r);
    		
    	}
    	return r;
    } 
    private int numSun(int i, int j) {
		int sum = 0;
    	while(i>=10) {
    		sum+=i%10;
    		i = i/10;
    	}
    	while(j>=10) {
    		sum+=j%10;
    		j = j/10;
    	}
    	sum+=i;sum+=j;
		return sum;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章