In-depth studies of algorithms for solving motion planning problems have been conducted due to the rapid popularization and development of unmanned aerial vehicles in previous decades. Among them, the classic rapidly exploring random tree (RRT) algorithm has derivative algorithms (e.g., RRT*, Q-RRT*, and F-RRT*) that focus on the optimal path cost of the initial solution. Other improved algorithms, such as RRT-connect and BG-RRT, focus on the optimal time of the initial solution. This article proposes an improved density gradient-RRT (DG-RRT) algorithm based on RRT that improves the efficiency of the guide point and reduces the time lost in the process of obtaining the initial solution through the dynamic gradient sampling strategy. Simultaneously, it reduces the path cost by reconstructing the output path. The proposed algorithm is an expansion algorithm of a random tree, and the performance of the algorithm can be further improved by combining it with other RRT optimization algorithms. DG-RRT and other algorithms are compared in different environments through simulation experiments to verify the advantages of DG-RRT. In addition, it used a set of simulation flight tests to verify the feasibility of the DG-RRT algorithm for UAV path planning.