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 ch1: chs1){ sum += Character.getNumericValue(ch1); } return sum<=t; } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解mybatis-plus使用@EnumValue注解的方式對枚舉類型的處理
這篇文章主要介紹了詳解mybatis-plus使用@EnumValue注解的方式對枚舉類型的處理,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12java selenium 常見web UI 元素操作及API使用
本文主要介紹java selenium 常見web UI 元素操作,這里幫大家整理了相關(guān)資料并附示例代碼,有需要的小伙伴可以參考下2016-08-08一文詳解Java中的可變對象(Mutable)與不可變對象(Immutable)
如何在 Java 中創(chuàng)建不可變對象?我以前以為所有對象都是不可變的,因為如果你改變一個 String 實例的內(nèi)容,它總是會創(chuàng)建一個新的 String 對象并指向該對象,在本文中,我不僅將分享在 Java 中Immutable的步驟,還將討論可變對象與不可變對象及其優(yōu)缺點2023-11-11