题解 | #机器人的运动范围#
机器人的运动范围
http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
- 当遇到不可走的时候,务必要return(),否则就会以错误的点为基础继续走下下一个点的(实际这个点都走不到,那继续往下走肯定是错的)
- 时时注意索引和x,y的配合
class Solution { public: //位置数组 int dx[4] = {0,0,-1,1}; int dy[4] = {-1,1,0,0}; int cal(int x, int y){ int sum = 0; while(x){ sum+=x%10; x/=10; } while(y){ sum+=y%10; y/=10; } return sum; } void back_trace(int threshold, int row, int col,vector<vector<int>> &visits, int &sum,int rows, int cols){ //base case 2 if(cal(row,col)<=threshold){ sum++; }else{ return; } visits[row][col] = 1;//标记访问位置 for(int i = 0; i< 4; i++){ int newx = col + dx[i]; int newy = row + dy[i]; if(newx<0||newx>=cols||newy<0||newy>=rows){ continue; } if(visits[newy][newx]==0){ back_trace(threshold,newy,newx,visits,sum,rows,cols); } } } int movingCount(int threshold, int rows, int cols) { if(!rows||!cols) return 0; vector<vector<int>> visits(rows,vector<int>(cols,0)); int sum = 0; back_trace(threshold,0,0,visits, sum,rows,cols); return sum; } };
剑指Offer 文章被收录于专栏
剑指offer的解析结合