這篇文章主要為大家展示了“java如何計算機器人的運動范圍”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學習一下“java如何計算機器人的運動范圍”這篇文章吧。

機器人的運動范圍java版,具體內(nèi)容如下
地上有一個m行和n列的方格。一個機器人從坐標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行坐標和列坐標的數(shù)位之和大于k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
解題思路:
1.首先判斷當前位置是否滿足進入條件,若滿足可進入條件,則繼續(xù)判斷其周圍上下左右的四個位置(除邊界外)。若不滿足,則說明當前位置選取錯誤。
2.在每次的嘗試中,聲明一個標志數(shù)組,來記錄已經(jīng)訪問過的位置。
3.當前嘗試繼續(xù)的條件有三個:坐標在矩陣中位置合法,坐標滿足可進入條件,坐標位置未訪問過。
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;
}
//計算坐標的位數(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 ch2: chs1){
sum += Character.getNumericValue(ch2);
}
return sum<=t;
}
}以上是“java如何計算機器人的運動范圍”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
新聞名稱:java如何計算機器人的運動范圍-創(chuàng)新互聯(lián)
文章源于:http://www.chinadenli.net/article20/ipcco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、定制開發(fā)、App設(shè)計、關(guān)鍵詞優(yōu)化、微信公眾號、電子商務
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)