657.Judge Route Circle(判断环形路径)

657.Judge Route Circle(判断环形路径)

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L(Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

Example 1:

Input: “UD”

Output: true

Example 2:

Input: “LL”

Output:false

题意

开始给在原点(0,0)位置的机器人,给出一系列它的移动,判断机器人是否移动了一个环,即机器人是否回到了初始的位置。

移动的操作用一个字符串给出,每一个字符代表一种行动,有效的操作分为R(向右),L(向左),U(向上),D(向下)。输出true或者false来表示机器人是否花了一个环。

思路

机器人只会向上下左右四个方向移动,我们可以认为机器人的移动分为水平方向移动和竖直方向移动,如果水平方向上移动的距离为0,竖直方向上移动的距离也为0,则机器人会回到初始位置,否则,机器人回不到初始位置。用x来代表水平方向上移动的距离,规定向右为正方向,即向右移动,执行x+1,向左移动x-1。用y来代表竖直方向上移动的距离,规定向上为正方向,即向上移动,执行y+1,向下移动y-1。最后判断x和y是否都为0,如果都为0,则代表回到了初始位置,否则代表没有回到初始位置。

代码(C++)

class Solution {

public:

    bool judgeCircle(string moves) {

        int x = 0 , y = 0 ;

        for( int i = 0 ; i < moves.size() ; ++ i ){

            if( moves[i] == 'U' )

                ++ y;

            if( moves[i] == 'D' )

                -- y;

            if( moves[i] == 'R' )

                ++ x;

            if( moves[i] == 'L' )

                -- x;

        }

        if( x == 0 && y == 0 )

            return true;

        else

            return false;

    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值