I am trying write a program capable of converting rotation matrix into euler angles when gimbal lock occurs.
Is it even possible to determine the raw,pitch yaw angles when the matrix contains gimbal lock, and if so how?
This answer explains when gimbal lock occurs: Euler angles and gimbal lock
This answer covers the topic of quaternions, specifically how quaternions avoid the problem of gimbal lock: What is the motivation for quaternions?
It's your choice whether you want your program to remain in the Euler angle world and fudge the gimbal lock problem manually, or whether you want to convert to/from quaternions instead. R has a nice package for converting between rotation matrices, Euler angles, and quaternions: https://cran.r-project.org/web/packages/RSpincalc/index.html