机器人的运动范围
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
package com.test; public class RobotMove { int[] matrix = null; boolean isRight(int rowpos,int colpos,int threshold){ String rowpo = Integer.toString(rowpos); String colpo = Integer.toString(colpos); int sum = 0; for(int i = 0;i < rowpo.length(); i++) sum += (rowpo.charAt(i)-'0'); for(int i = 0;i < colpo.length(); i++) sum += (colpo.charAt(i)-'0'); if(sum>threshold) return false; return true; } void Cover(int threshold,int rowpos,int colpos,int rows,int cols){ if((rowpos+1)<rows&&colpos<cols&&isRight(rowpos+1,colpos,threshold)&&matrix[(rowpos+1)*cols+colpos]==0){ matrix[(rowpos+1)*cols+colpos] = 1; Cover(threshold,rowpos+1,colpos,rows,cols); } if(rowpos<rows&&(colpos+1)<cols&&isRight(rowpos,colpos+1,threshold)&&matrix[rowpos*cols+colpos+1]==0){ matrix[rowpos*cols+colpos+1] = 1; Cover(threshold,rowpos,colpos+1,rows,cols); } if(rowpos-1>=0&&colpos<cols&&isRight(rowpos-1,colpos,threshold)&&matrix[(rowpos-1)*cols+colpos]==0){ matrix[(rowpos-1)*cols+colpos] = 1; Cover(threshold,rowpos-1,colpos,rows,cols); } if(rowpos<rows&&colpos-1>=0&&isRight(rowpos,colpos-1,threshold)&&matrix[rowpos*cols+colpos-1]==0){ matrix[rowpos*cols+colpos-1] = 1; Cover(threshold,rowpos,colpos-1,rows,cols); } } public int movingCount(int threshold, int rows, int cols) { if(threshold<0) return 0; matrix = new int[rows*cols]; for(int i = 0;i < rows*cols; i++) matrix[i] = 0; matrix[0] = 1; Cover(threshold,0,0,rows,cols); int count = 0; for(int i = 0;i < rows*cols; i++){ // System.out.print(matrix[i]+" "); // if(i%cols==(cols-1)) // System.out.println(); if(matrix[i]==1) count++; } return count; } public static void main(String[] args) { // TODO Auto-generated method stub RobotMove rm = new RobotMove(); System.out.println(rm.movingCount(5,10,10)); } }