zoukankan      html  css  js  c++  java
  • 剑指office--------机器人的运动范围

    题目描述

    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
     
     
     
     
     1 class Solution {
     2 public:
     3     bool judge(int shreshold,int rows,int cols){
     4         int ans=0;
     5         while (rows){
     6             ans=ans+rows%10;
     7             rows/=10;
     8         }
     9         while (cols){
    10             ans=ans+cols%10;
    11             cols/=10;
    12         }
    13         if (shreshold>=ans)
    14             return true;
    15         return false;
    16     }
    17     void bfs(int shreshold,int rows,int cols,int &ans){
    18         const int m=rows,n=cols;
    19         bool vis[m+10][n+10];
    20         for (int i=0;i<m;i++)
    21             for (int j=0;j<n;j++)    vis[i][j]=true;
    22         vis[0][0]=false;
    23         struct s{
    24             int x,y;
    25         }mp;
    26         int dir[4][2]={1,0,0,1,-1,0,0,-1};
    27         queue<s>q;
    28         while (!q.empty())    q.pop();
    29         mp.x=mp.y=0;
    30         q.push(mp);
    31         while (!q.empty()){
    32             s node,temp=q.front();
    33             q.pop();
    34             for (int k=0;k<4;k++){
    35                 node.x=temp.x+dir[k][0];
    36                 node.y=temp.y+dir[k][1];
    37                 if (node.x>=0&&node.x<rows&&node.y>=0&&node.y<cols&&vis[node.x][node.y]&&judge(shreshold, node.x, node.y)){
    38                     q.push(node);
    39                     vis[node.x][node.y]=false;
    40                     ans++;
    41                 }
    42             }
    43         }
    44         return ;
    45     }
    46     int movingCount(int threshold, int rows, int cols)
    47     {
    48         if (threshold<0||rows<0||cols<0)    return 0;
    49         int ans=1;    
    50         bfs(threshold,rows,cols,ans);
    51         return ans;
    52     }
    53 };

    很常规的题目

  • 相关阅读:
    [ProjectEuler.net] 14
    Design patterns
    初等函数定义
    Design patterns 1.6 Design for change
    Programming In Haskell chapter3
    桌面恶心的无法删除的图标之 淘宝购物 删除办法
    程序员学英语三部曲
    e的给定精度求法
    Summary about Architect Visit
    再谈“我是怎么招聘程序员的”(上)
  • 原文地址:https://www.cnblogs.com/q1204675546/p/13362545.html
Copyright © 2011-2022 走看看