機器人的運動范圍java版,具體內(nèi)容如下
地上有一個m行和n列的方格。一個機器人從坐標(biāo)0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于k的格子。 例如,當(dāng)k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
解題思路:
1.首先判斷當(dāng)前位置是否滿足進入條件,若滿足可進入條件,則繼續(xù)判斷其周圍上下左右的四個位置(除邊界外)。若不滿足,則說明當(dāng)前位置選取錯誤。
2.在每次的嘗試中,聲明一個標(biāo)志數(shù)組,來記錄已經(jīng)訪問過的位置。
3.當(dāng)前嘗試?yán)^續(xù)的條件有三個:坐標(biāo)在矩陣中位置合法,坐標(biāo)滿足可進入條件,坐標(biāo)位置未訪問過。
public class Solution { public int movingCount(int threshold, int rows, int cols) { if(threshold<0 || rows<=0 || cols<=0){ return 0; } int count = 0; boolean[] flag = new boolean[rows*cols]; for(int i=0; i<rows*cols; i++){ flag[i] = true; } count = Moving(threshold, 0, 0, rows, cols, flag); return count; } public int Moving(int t, int row, int col, int rows, int cols, boolean[] flag){ int count = 0; if(isAllow(t, row, col, rows, cols, flag)){ flag[row*cols+col] = false; count = 1+Moving(t, row-1, col, rows, cols, flag)+Moving(t, row, col-1, rows, cols, flag)+Moving(t, row+1, col, rows, cols, flag)+Moving(t, row, col+1, rows, cols, flag); } return count; } //計算坐標(biāo)的位數(shù)和,返回與threshold的比較結(jié)果 public boolean isAllow(int t, int row, int col, int rows, int cols, boolean[] flag){ if(row>rows ||row<0 || col>cols || col<0 || row*cols+col>rows*cols-1|| flag[row*cols+col]==false){ return false; } int sum = 0; char[] chs = (row+"").toCharArray(); char[] chs1= (col+"").toCharArray(); for(char ch: chs){ sum += Character.getNumericValue(ch); } for(char ch1: chs1){ sum += Character.getNumericValue(ch1); } return sum<=t; }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點
疑難解答
圖片精選