From 2eec43c9a803673b0125a3a062b95299b79a0fc1 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Sun, 9 Jan 2022 17:52:10 +0800 Subject: [PATCH] add: 220109 --- 2201/220109.cpp | 56 +++++++++++++++++++++++++++++++++++++++++++++ 2201/CMakeLists.txt | 2 +- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 2201/220109.cpp diff --git a/2201/220109.cpp b/2201/220109.cpp new file mode 100644 index 0000000..8b0556f --- /dev/null +++ b/2201/220109.cpp @@ -0,0 +1,56 @@ +#include +#include + +/** + * 1041. Robot Bounded In Circle + * On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: + * "G": go straight 1 unit; + * "L": turn 90 degrees to the left; + * "R": turn 90 degrees to the right. + * The robot performs the instructions given in order, and repeats them forever. + * Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. + */ + +class Solution { +private: + // N, E, S, W + inline static int dX[4] = {0, 1, 0, -1}; + inline static int dY[4] = {1, 0, -1, 0}; +public: + static bool isRobotBounded(std::string instructions) { + // instructions = instructions * 8; + instructions.append(instructions); + instructions.append(instructions); + instructions.append(instructions); + + int l = instructions.length(); + int X = 0, Y = 0, D = 0; + const char* const str = instructions.c_str(); + for (int i = 0; i < l; ++i) { + switch (str[i]) { + case 'G': + X += dX[D]; + Y += dY[D]; + break; + case 'L': + D = (D + 3) % 4; + break; + case 'R': + D = (D + 1) % 4; + break; + default: + ; // Should never reach here. + } + if (!X && !Y && !D && !std::strncmp(str, str + i + 1, i + 1)) { + return true; + } + } + return false; + } +}; + +int main() { + bool ans = Solution::isRobotBounded("GL"); + std::cout << ans; + return 0; +} \ No newline at end of file diff --git a/2201/CMakeLists.txt b/2201/CMakeLists.txt index e54904b..c2299eb 100644 --- a/2201/CMakeLists.txt +++ b/2201/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2201) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2201 220109-CN.cpp) \ No newline at end of file +ADD_EXECUTABLE(2201 220109.cpp) \ No newline at end of file