import collections


class Solution(object):
    def isRobotBounded(self, instructions):
        """
        :type instructions: str
        :rtype: bool
        """
        dirs = collections.defaultdict(collections.defaultdict)
        dirs['N'] = {'L': 'W', 'R': 'E'}
        dirs['S'] = {'L': 'E', 'R': 'W'}
        dirs['W'] = {'L': 'S', 'R': 'N'}
        dirs['E'] = {'L': 'N', 'R': 'S'}

        steps = {}
        steps['N'], steps['S'], steps['W'], steps['E'] = (0, 1), (0, -1), (-1, 0), (1, 0)

        dir, L, step, x, y = 'N', len(instructions), 0, 0, 0

        while step < 4 * L:
            if instructions[step % L] == 'G':
                x, y = x + steps[dir][0], y + steps[dir][1]
            else:
                dir = dirs[dir][instructions[step % L]]

            step += 1

        return x == 0 and y == 0


if __name__ == '__main__':
    print Solution().isRobotBounded("RRGRRGLLLRLGGLGLLGRLRLGLRLRRGLGGLLRRRLRLRLLGRGLGRRRGRLG")
    print Solution().isRobotBounded("GGLLGG")
    print Solution().isRobotBounded("GL")
    print Solution().isRobotBounded("GG")
