百度面试题——裁剪网格纸

这是一道关于算法的问题,度度熊需要在网格纸上裁剪一个正方形,确保所有点位于正方形内或边界上。通过计算x和y坐标的最大差值得到正方形边长,从而得出最小面积。算法思路是找到坐标的最大差值并取最大值作为正方形边长,然后输出该边长的平方作为最小面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

度度熊有一张网格纸,但是纸上有一些点过的点,每个点都在网格点上,若把网格看成一个坐标轴平行于网格线的坐标系的话,每个点可以用一对整数x,y来表示。度度熊必须沿着网格线画一个正方形,使所有点在正方形的内部或者边界。然后把这个正方形剪下来。问剪掉正方形的最小面积是多少。

输入描述:

第一行一个数n(2≤n≤1000)表示点数,接下来每行一对整数xi,yi(-1e9<=xi,yi<=1e9)表示网格上的点

输出描述:

一行输出最小面积

输入例子:

2
0 0
0 3

输出例子:

9

分析:

分别求得x坐标和y坐标的最大差值,再求二者的最大值。

算法代码:

int cutGridPaper(int n, int X[], int Y[])
{
    int minimunArea = 0;
    
    int minXLength, maxXLength, minYLength, maxYLength, XLength, YLength;
    
    minXLength = maxXLength = X[0];
    minYLength = maxYLength = Y[0];
    
    for (int i = 0; i < n; ++i) {
        if (X[i] > maxXLength) {
            maxXLength = X[i];
        }
        if (X[i] < minXLength) {
            minXLength = X[i];
        }
        if (Y[i] > maxYLength) {
            maxYLength = Y[i];
        }
        if (Y[i] < minYLength) {
            minYLength = Y[i];
        }
    }
    
    XLength = abs(maxXLength - minXLength);
    YLength = abs(maxYLength - minYLength);
    
    if (XLength > YLength) {
        minimunArea = XLength * XLength;
    }
    else
    {
        minimunArea = YLength * YLength;
    }
    
    return minimunArea;
}

测试代码:

//
//  main.cpp
//  cutGridPaper
//
//  Created by Jiajie Zhuo on 2017/4/23.
//  Copyright © 2017年 Jiajie Zhuo. All rights reserved.
//

#include <iostream>
#include <cmath>

using namespace std;

int cutGridPaper(int n, int X[], int Y[]);

int main(int argc, const char * argv[]) {
    int n;
    cout << "Please enter the number of point n: ";
    cin >> n;

    int X[n];
    int Y[n];
    cout << "Please enter the coordinates of points: ";
    for (int i = 0; i < n; ++i) {
        cin >> X[i] >> Y[i];
    }
    
    cout << "The minimun area of the square is " << cutGridPaper(n, X, Y) << endl;
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值