码迷,mamicode.com
首页 > 其他好文 > 详细

机器人走方格

时间:2015-12-05 21:03:15      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

package Solutions;

import java.util.ArrayDeque;
import java.util.Queue;

/**
* Created by hu on 2015/12/5.
*/
/*
题目描述:
*地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,
* 但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
* 但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
* */
public class solution23 {
public static int movingCount(int threshold, int rows, int cols)
{
if(threshold<0){
return 0;
}
//首先建立一个代表所有格子的矩阵,其中的每一个元素都为0,如果机器人能够到达就置为1
int[][] matrix=new int[rows][cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
matrix[i][j]=0;
}
}
//矩阵的每一个元素为1,代表机器人能够到达
//建立一个队列,队列里存储的是机器能够到达的方格,初始为mattrix[0][0]
Queue<RowAndCol> queue=new ArrayDeque<RowAndCol>();
RowAndCol first=new RowAndCol(0,0);
//count是机器人能够达到的方格个数
int count=1;
matrix[0][0]=1;
queue.add(first);
while (!queue.isEmpty()){
RowAndCol temp=queue.remove();
int row=temp.getRow();
int col=temp.getCol();
//构造上,下,左,右四个方格
if(row>0){
RowAndCol top=new RowAndCol(row-1,col);
if(matrix[row-1][col]==0&&top.getSum()<=threshold){
queue.add(top);
matrix[row-1][col]=1;
count=count+1;
}
}
if(row<rows-1){
RowAndCol bottom=new RowAndCol(row+1,col);
if(matrix[row+1][col]==0&&bottom.getSum()<=threshold){
queue.add(bottom);
matrix[row+1][col]=1;
count=count+1;
}
}
if(col>0){
RowAndCol left=new RowAndCol(row,col-1);
if(matrix[row][col-1]==0&&left.getSum()<=threshold){
queue.add(left);
matrix[row][col-1]=1;
count=count+1;
}
}
if(col<cols-1){
RowAndCol right=new RowAndCol(row,col+1);
if(matrix[row][col+1]==0&&right.getSum()<=threshold){
queue.add(right);
matrix[row][col+1]=1;
count=count+1;
}
}
}
return count;
}
public static void main(String[] args){
System.out.print(movingCount(-10,10,10));
}
}
class RowAndCol{
private int row;
private int col;
private int sum;
public RowAndCol(int row,int col){
this.row=row;
this.col=col;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public int getSum() {
return addRowAndCol(row)+addRowAndCol(col);
}
private int addRowAndCol(int n){
int result=0;
while (n!=0){
int temp=n%10;
result=temp+result;
n=n/10;
}
return result;
}
}

机器人走方格

标签:

原文地址:http://www.cnblogs.com/hujingwei/p/5022231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!