劍指offer 67題 【回溯法】機器人的運動範圍

題目描述

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

牛客傳送門:點擊打開鏈接

public class Title67 {
	int[] visited;
	int row,col;
	public int movingCount(int threshold, int rows, int cols)
    {
		if(threshold <0)
			return 0;
        visited = new int[rows * cols];
        row = rows;col = cols;
        
        moving(threshold,0,0);
        
        int count =1;
        for(int i=0;i<row;i++){
        	for(int j=0;j<col;j++){
        		if(visited[i*col+j] == 1)
        			count++;
        	}
        }
        
        return count-1; // 去除0,0
    }
	
	public void moving(int threshold,int i,int j){
		
		if(check(threshold,i,j) == false)
			return ;
		System.out.println(i+" "+j);
		visited[i*col+j] = 1;
		moving(threshold,i-1,j);
		moving(threshold,i+1,j);
		moving(threshold,i,j-1);
		moving(threshold,i,j+1);
		
	}

	boolean check(int threshold,int i,int j){
		if(i < 0 || i>= row || j<0 || j>=col || visited[i*col+j] == 1){
			return false;
		}
		
		int sum = 0;
		while(i >0){
			sum += i%10;
			i /= 10;
		}
		while(j >0){
			sum += j%10;
			j /=10;
		}
		if(sum > threshold)
			return false;
		return true;
	}
	
	public static void main(String[] args) {
		Title67 clazz = new Title67();
		System.out.println(clazz.movingCount(5, 10, 10));
	}
}


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