max-points-on-a-line



leetcode的一道题

在平面内若干个点中,求出在同一直线上点数最多的点数。

用穷举法



/**

 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    int maxPoints(vector<Point> &points) {
        if(points.size() == 0) return 0;
        else if(points.size() == 1) return 1;
        int res = 2;
        for(int i = 0; i < points.size(); i++){
            
            int sameP = 0;
            int vert = 0;
            unordered_map<double, int>  km;
            for(int j = i + 1; j < points.size(); j++){
                
                int dy = points[i].y - points[j].y;
                int dx = points[i].x - points[j].x;
                if(dx == 0)
                {
                    if(dy == 0){
                        sameP++;
                    }
                    else{
                        vert++;
                    }
                    
                }
                else{
                    double k = dy / double(dx);    
                    km[k]++;
                }
            }
            int max_n = vert; 
            for(const auto &temp : km){
if(temp.second > max_n)
                    max_n = temp.second;
            }
            max_n = max_n + sameP + 1;
            res = (res > max_n ? res : max_n);
        }
        return res;
    }

};


其中的坑点::36行要注意把整数强制转化为浮点数。

我一开始没住意,坑了我半小时,去想是不是哪儿逻辑有问题。

谨记c++的这种坑,以后别犯这种低级错了

### APF-RRT Algorithm Implementation and Explanation #### Overview of the APF-RRT Algorithm The Artificial Potential Field (APF)-Rapidly-exploring Random Tree (RRT) algorithm combines two powerful concepts from robotics to achieve efficient path planning while avoiding obstacles. The RRT method is adept at exploring complex environments, whereas the APF approach provides a mechanism for guiding this exploration with attractive forces toward goals and repulsive forces away from obstacles. In an environment where paths need to be planned dynamically around static or moving objects, integrating these methods can yield robust solutions that are both computationally feasible and effective in real-world applications[^1]. #### Key Components of the APF-RRT Methodology To understand how APF-RRT works, it's important to break down its components: - **Artificial Potential Fields**: These fields create virtual force vectors within the robot’s configuration space. An attractive potential pulls the robot towards the target location, while repulsive potentials push the robot away from detected obstacles. - **Rapidly Exploring Random Trees**: This technique builds a tree structure incrementally by adding nodes sampled randomly throughout free space until reaching close proximity to the goal position. Each node represents possible configurations of the robotic system being controlled. By combining artificial potential field theory with rapidly exploring random trees, one obtains enhanced capabilities over using either alone; specifically better handling of narrow passages between obstacles due to guided sampling influenced by gradient information provided through APFs[^2]. #### Practical Steps Towards Implementing APF-RRT Implementing such algorithms involves several key steps including defining parameters like step size during growth phase as well as tuning weights associated with attraction versus repulsion terms inside your cost function formulation used when calculating new branches off existing ones on growing tree structures representing reachable states within workspace boundaries set forth initially before execution begins. Below demonstrates Python code implementing basic functionality required for constructing simple versions suitable enough for educational purposes but not optimized fully nor guaranteed stable under all conditions encountered outside laboratory settings without further refinements tailored specifically per application domain requirements. ```python import numpy as np from scipy.spatial import KDTree class Node: def __init__(self, point, parent=None): self.point = point # Numpy array [x,y] self.parent = parent def steer(from_point, to_point, extend_length=.5): direction = np.array(to_point) - np.array(from_point) length = np.linalg.norm(direction) if length > extend_length: direction = (direction / length) * extend_length return tuple(np.round((np.array(from_point)+direction), decimals=3)) def generate_random_point(xlim, ylim): x = np.random.uniform(*xlim) y = np.random.uniform(*ylim) return (x, y) def nearest_neighbor(tree_nodes, random_point): closest_dist_sq = float('inf') closest_node = None kdtree = KDTree([n.point for n in tree_nodes]) _, idx = kdtree.query(random_point) return tree_nodes[idx] def collision_free(pointA, pointB, obstacle_list): min_distance_to_obstacle = .08 # Minimum distance to avoid collisions line_points = zip( np.linspace(pointA[0], pointB[0]), np.linspace(pointA[1], pointB[1]) ) for p in line_points: for obs in obstacle_list: dist_squared = sum([(p_i-o_i)**2 for p_i, o_i in zip(p,obs)]) if dist_squared < min_distance_to_obstacle**2: return False return True def rrt(start=(0., 0.), goal=(9., 9.), xlim=(-10, 10), ylim=(-10, 10), obstacle_list=[], max_iter=1e4, expand_dis=.2, search_until_maxiter=False): start_node = Node(start) tree_nodes = [start_node] for i in range(int(max_iter)): rnd_point = generate_random_point(xlim=xlim, ylim=ylim) near_node = nearest_neighbor(tree_nodes, rnd_point) new_point = steer(near_node.point, rnd_point, expand_dis) if collision_free(new_point=near_node.point, old_point=new_point, obstacle_list=obstacle_list): new_node = Node(new_point, parent=near_node) tree_nodes.append(new_node) if calculate_goal_dist(new_point, goal)<expand_dis: final_path = [] temp_node = new_node while temp_node: final_path.insert(0,temp_node.point) temp_node=temp_node.parent return final_path elif search_until_maxiter==False: continue raise ValueError("Cannot find path") ``` This example does not include full implementation details regarding integration with actual hardware interfaces or more sophisticated approaches needed for practical deployment scenarios involving dynamic changes occurring unpredictably across operational areas traversed autonomously via mobile platforms equipped appropriately according to task specifications outlined beforehand carefully considering safety concerns alongside performance metrics deemed critical success factors determining overall effectiveness achieved once deployed successfully into intended usage contexts established clearly prior starting development efforts aimed producing working prototypes capable demonstrating proof-of-concept validation confirming feasibility claims made earlier stages conceptualization process leading ultimately creation functional systems ready roll-out beyond experimental testing phases conducted laboratories controlled environments ensuring reliability levels sufficient supporting broader adoption rates seen industry sectors adopting similar technologies solving comparable challenges faced daily operations requiring intelligent automation support enhancing productivity gains realized through improved efficiencies gained leveraging advanced computational techniques applied effectively addressing specific needs identified stakeholders involved project lifecycle management activities carried out systematically following best practices recommended experts specializing relevant domains knowledge applicable situation hand.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值