地上有一個m行和n列的方格。一個機器人從坐標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行坐標和列坐標的數位之和大于k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
解題思路:
1.首先判斷當前位置是否滿足進入條件,若滿足可進入條件,則繼續判斷其周圍上下左右的四個位置(除邊界外)。若不滿足,則說明當前位置選取錯誤。
2.在每次的嘗試中,聲明一個標志數組,來記錄已經訪問過的位置。
3.當前嘗試繼續的條件有三個:坐標在矩陣中位置合法,坐標滿足可進入條件,坐標位置未訪問過。
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; } //計算坐標的位數和,返回與threshold的比較結果 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; } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/ouyangyanlan/article/details/72874647