标签:面试题 rows offer int 13 cols threshold col row
/* 题目: 地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始运动, 每次可向上、下、左、右移动一格,但不能进入行坐标和列坐标之和大于k的格子。 如,当k=18时,机器人能进入(35,37),因为3+5+3+7=18。 但不能进入(35,38),问机器人能够到达多少格子。 */ /* 思路: 递归法。 机器人从第一个格子走; 计算机器人向左、右、上、下可走的格子数之和。 使用visited进行标注,防止已走过的格子被重复计数。 */ #include<iostream> #include<string.h> #include<algorithm> using namespace std; bool isValid(int row,int col,int threshold){ int num = 0; while(row != 0){ num += row % 10; row = row / 10; } while(col != 0){ num += col % 10; col = col / 10; } return num > threshold ? false : true; } int movingCounCore(int row,int col,int rows,int cols,int threshold,bool* visited){ int myCount = 0; //cout<<row<<" "<<col<<endl; if(row >= 0 && col >=0 && row < rows && col < cols && !visited[cols*row+col] && isValid(row,col,threshold)){ visited[row*cols + col] = true; myCount = 1+movingCounCore(row+1,col,rows,cols,threshold,visited) + movingCounCore(row,col+1,rows,cols,threshold,visited) + movingCounCore(row-1,col,rows,cols,threshold,visited) + movingCounCore(row,col-1,rows,cols,threshold,visited); } return myCount; } int movingCount(int threshold,int rows,int cols){ if(threshold < 0 || rows <= 0 || cols <= 0){ return 0; } bool *visited = new bool[rows*cols]; memset(visited,false,rows*cols); int myCount = movingCounCore(0,0,rows,cols,threshold,visited); delete[] visited; return myCount; } int main(){ cout<<movingCount(5,2,2)<<endl; }
标签:面试题,rows,offer,int,13,cols,threshold,col,row 来源: https://www.cnblogs.com/buaaZhhx/p/11845170.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。