题解 | #机器人的运动范围#

机器人的运动范围

http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8

public class Solution {
    int count=0;
    boolean visited[][];
    public int movingCount(int threshold, int rows, int cols) {
        visited=new boolean[rows][cols];
       
           if(isOk(threshold,0,0) && visited[0][0]!=true)
              dfs(threshold,rows,cols,0,0);

        return count;
    }
    void dfs(int threshold,int rows,int cols,int x,int y)
    {
        count++;
        visited[x][y]=true;
        //left
        if(  y-1>=0 && isOk(threshold,x,y-1) && visited[x][y-1]!=true)
            dfs(threshold,rows,cols,x,y-1);
        //down
         if(x+1<rows && isOk(threshold,x+1,y) && visited[x+1][y]!=true )
            dfs(threshold,rows,cols,x+1,y);
        //right
         if(y+1<cols && isOk(threshold,x,y+1) && visited[x][y+1]!=true  )
            dfs(threshold,rows,cols,x,y+1);
        //up
         if(x-1>=0&&isOk(threshold,x-1,y) && visited[x-1][y]!=true  )
            dfs(threshold,rows,cols,x-1,y);
         
    }
    boolean isOk(int threshold,int x, int y)
    {
        return (sum(x)+sum(y))<=threshold;
    }
    int sum(int val)
    {
        int sum=0;
        int temp=val;
        while(temp>0)
        {
             sum=sum+temp%10;
             temp=temp/10;
        }
        return sum;
    }
    
}

全部评论

相关推荐

02-10 13:41
西南大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务