機(jī)器人的運(yùn)動(dòng)范圍java版,具體內(nèi)容如下
地上有一個(gè)m行和n列的方格。一個(gè)機(jī)器人從坐標(biāo)0,0的格子開始移動(dòng),每一次只能向左,右,上,下四個(gè)方向移動(dòng)一格,但是不能進(jìn)入行坐標(biāo)和列坐標(biāo)的數(shù)位之和大于k的格子。 例如,當(dāng)k為18時(shí),機(jī)器人能夠進(jìn)入方格(35,37),因?yàn)?+5+3+7 = 18。但是,它不能進(jìn)入方格(35,38),因?yàn)?+5+3+8 = 19。請(qǐng)問該機(jī)器人能夠達(dá)到多少個(gè)格子?
解題思路:
1.首先判斷當(dāng)前位置是否滿足進(jìn)入條件,若滿足可進(jìn)入條件,則繼續(xù)判斷其周圍上下左右的四個(gè)位置(除邊界外)。若不滿足,則說明當(dāng)前位置選取錯(cuò)誤。
2.在每次的嘗試中,聲明一個(gè)標(biāo)志數(shù)組,來記錄已經(jīng)訪問過的位置。
3.當(dāng)前嘗試?yán)^續(xù)的條件有三個(gè):坐標(biāo)在矩陣中位置合法,坐標(biāo)滿足可進(jìn)入條件,坐標(biāo)位置未訪問過。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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; } //計(jì)算坐標(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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/ouyangyanlan/article/details/72874647