We have proposed the sway compensation trajectory of robot body to realize dynamically stable walking for a quadruped walking robot. This method uses the lateral motion of the robot body to keep a zero momentum point (ZMP) on a diagonal line between the support legs. However, energy consumption of the sway compensation trajectory is larger than the case without trajectory control because periodical acceleration of the body has to be generated to realize sway motion. In this paper, we propose a new sway compensation trajectory for a quadruped walking robot named 3D sway compensation trajectory. This method is the extension of conventional sway compensation trajectory toward three dimensional motion, and the position of ZMP is controlled not only by lateral body motion but also by longitudinal and vertical body motion. Next, we demonstrate that energy consumption for walking can be reduced by combining these motions through theoretical analysis and computer simulation, and an optimum 3D sway compensation trajectory that minimizes energy consumption is proposed. Optimum trajectory is applied to a quadruped walking robot and the validity of the proposed trajectory is verified using the dynamic motion simulator, ADAMS.