zoukankan      html  css  js  c++  java
  • 机器人走方格

    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;
    }
    }
  • 相关阅读:
    SQL Server 2012提供的OFFSET/FETCH NEXT与Row_Number()对比测试
    sql 知识点
    javascript基础拾遗——词法作用域
    Linux 软件包管理
    涉略spring
    WebReBuild年会流水记
    javascript面向对象学习笔记(一)——继承
    算法学习——动态规划策略入门
    编程之美读书笔记——2.3寻找水王
    Linux 引导流程解析
  • 原文地址:https://www.cnblogs.com/hujingwei/p/5022231.html
Copyright © 2011-2022 走看看