求白色三角形的最大面积 Triangles

本文深入探讨了游戏开发领域的核心技术,包括游戏引擎、动画、3D空间视频等,旨在为开发者提供全面的游戏开发知识和实践经验。

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

Triangles

It is always very nice tohave little brothers or sisters. You can tease them, lock them in the bathroomor put red hot chili in their sandwiches. But there is also a time when allmeanness comes back!

As you know, in one month it is Christmasand this year you are honored to make the big star that will be stuck on thetop of the Christmas tree. But when you get the triangle-patterned silver paperyou realize that there are many holes in it. Your little sister has already cutout smaller triangles for the normal Christmas stars. Your only chance is tofind an algorithm that tells you for each piece of silver paper the size of thelargest remaining triangle.

Given a triangle structure with white andblack fields inside you must find the largest triangle area of white fields, asshown in the following figure.


Input

The input contains several triangle descriptions. The first line of eachdescription contains an integer n (1 <= n <= 100), which gives the heightof the triangle. The next n lines contain characters of the set {space, #, -}representing the rows of the triangle, where `#' is a black and `-' a whitefield. The spaces are used only to keep the triangle shape in the input bypadding at the left end of the lines. (Compare with the sample input. The firsttest case corresponds to the figure.) 
For each triangle, the number of the characters `#' and `-' per line is odd anddecreases from 2n - 1 down to 1.

The input is terminated by a descriptionstarting with n = 0.


Output 

For each triangle in the input, first output the number of the triangle, asshown in the sample output. Then print the line ``The largest triangle area isa.'', where a is the number of fields inside the largest triangle that consistsonly of white fields. Note that the largest triangle can have its point at thetop, as in the second case of the sample input.

Output a blank line after each test case.


Sample Input

5
#-##----#
 -----#-
  ---#-
   -#-
    -
4
#-#-#--
 #---#
  ##-
   -
0


Sample Output

Triangle #1
The largest triangle area is 9.

Triangle #2
The largest triangle area is 4.

 

题目意思描述:找出图中白色三角形的最大面积,并输出。题目中用#表示黑色的三角形,用-表示白色三角形。

解题思路:最初想按照三角形的三个表来扩展查找,发现太麻烦了。然后仔细观察图中的三角形可知,图中的三角形只有两种形式:向上的三角形和向下的三角形(以顶点区分)。如果用node[i][i]开始存储第i行输入的数据,我们可以发现:

1、对任意一结点node[i][j](i,j都合理),如果i+j为偶数,那么该三角形是向下的,反之为向上的。

2、以某个三角形为开头的三角形面积为其对应最大三角形层数的平方,所以,用数组存储该点为三角形开头的最大三角形层数。

所以我们从向上和向下两个方向寻找最大三角形层数。以向下为例:

a[i][j]如果是白色,就判断正上方(正下方)是否为白色,如果是,就在正上方(正下方)三角形两侧得三角形中取最小层数,加在a[i][j]上;最后求出最大层数,计算出面积。

具体代码如下:

 

#include<iostream>

usingnamespace std;

 

#definemax 101

 

typedefstruct

{

    int level;//当前结点的最大层数

    char ch;//当前结点的符号表示

}Node;

Nodenode[2*max][2*max];

 

 

intmain()

{

    int n;//n表示输入的值

    int cishu=1;

    cin>>n;

    while(n!=0)

    {

        for(int i=0;i<2*n;i++)

        {

            for(int j=0;j<2*n;j++)

            {

                node[i][j].level=0;

                node[i][j].ch=' ';

            }

        }

        for(int i=0;i<n;i++)

        {

            for(int j=i;j<2*n-i-1;j+=1)

            {

                cin>>node[i][j].ch;

                if(node[i][j].ch=='-')

                    node[i][j].level=1;

            }

        }

        //往下寻找三角形

        for(int i=1;i<n;i++)

        {

            for(int j=i;j<2*n-i-1;j+=2)

            {

                //i+j为jishu

                if(node[i][j].ch =='-')

                {

                    if(node[i-1][j].ch=='-')

                    {

                        node[i][j].level+=node[i-1][j-1].level<node[i-1][j+1].level?node[i-1][j-1].level:node[i-1][j+1].level;

                    }

                }

            }

        }

        //往上寻找三角形

        for(int i=n-3;i>=0;i--)

        {

            for(int j=i+1;j<2*n-i-1;j+=2)

            {

                if(node[i][j].ch =='-')

                {

                    if(node[i+1][j].ch=='-')

                    {

                        node[i][j].level+=node[i+1][j-1].level<node[i+1][j+1].level?node[i+1][j-1].level:node[i+1][j+1].level;

                    }

                }

            }

        }

        int maxn=0;

        for(int i=0;i<n;i++)

        {

            for(int j=i;j<2*n-i-1;j+=1)

            {

                if(node[i][j].level>maxn)

                    maxn=node[i][j].level;

            }

        }

        cout<<"Triangle#"<<cishu<<endl;

        cishu+=1;

        cout<<"The largest trianglearea is "<<maxn*maxn<<"."<<endl;

        cout<<endl;

        cin>>n;//下一次输入

    }

    return 0;

}

 

 

import sensor import image import lcd import time from machine import UART # 初始化LCD lcd.init() # 初始化摄像头 sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QQVGA) # 160x120分辨率 sensor.skip_frames(time=3000) # 等待摄像头稳定 # 三角形检测参数设置 min_area = 1000 # 最小区域面积 max_area = 30000 # 最大区域面积 threshold = 5000 # 三角形检测阈值(越大越严格) # 主循环 while True: img = sensor.snapshot() # 捕获图像 # 转换为灰度图 gray = img.to_grayscale(copy=True) # 二值化处理(假设背景为白色三角形为黑色) binary = gray.binary([(0, 60)], invert=True) # 查找三角形 triangles = binary.find_triangles(threshold=threshold, area_threshold=(min_area, max_area)) # 处理检测到的三角形 for t in triangles: # 获取三角形的三个角点 p1, p2, p3 = t.corners() # 计算三角形的宽度和高度 width = max(p1[0], p2[0], p3[0]) - min(p1[0], p2[0], p3[0]) height = max(p1[1], p2[1], p3[1]) - min(p1[1], p2[1], p3[1]) # 计算三角形中心点 center_x = (p1[0] + p2[0] + p3[0]) // 3 center_y = (p1[1] + p2[1] + p3[1]) // 3 # 计算三角形外接矩形位置 min_x = min(p1[0], p2[0], p3[0]) min_y = min(p1[1], p2[1], p3[1]) # 绘制红色矩形框(BGR格式) img.draw_rectangle(min_x, min_y, width, height, color=(255, 0, 0), thickness=2) # 显示尺寸文本 img.draw_string(min_x, min_y-20, "W:%.1f H:%.1f" % (width, height), color=(255, 0, 0), scale=1.2) # 显示图像 lcd.display(img) # 可选: 通过串口输出数据 # print("Detected triangles:", len(triangles)) 基于上一个问题帮我修改这串代码然后将正确无误的代码完整的告诉我
最新发布
08-01
import sensor, image, time, math sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time=2000) # 霍夫变换检测直线 def detect_triangles(img): lines = img.find_lines(threshold=1000, theta_margin=25, rho_margin=25) candidates = [] # 寻找可能的三角形边 for i in range(len(lines)): for j in range(i+1, len(lines)): for k in range(j+1, len(lines)): l1, l2, l3 = lines[i], lines[j], lines[k] # 计算交点 p1 = line_intersection(l1, l2) p2 = line_intersection(l2, l3) p3 = line_intersection(l3, l1) if p1 and p2 and p3: # 计算三角形面积 area = abs((p1[0]*(p2[1]-p3[1]) + p2[0]*(p3[1]-p1[1]) + p3[0]*(p1[1]-p2[1]))/2) if area > 100: # 过滤小面积 candidates.append((p1, p2, p3)) return candidates # 计算两条直线的交点 def line_intersection(line1, line2): x1, y1, x2, y2 = line1.line() x3, y3, x4, y4 = line2.line() denom = (y4-y3)*(x2-x1) - (x4-x3)*(y2-y1) if denom == 0: # 平行线 return None ua = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / denom ub = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / denom if 0 <= ua <= 1 and 0 <= ub <= 1: # 线段相交 x = x1 + ua*(x2-x1) y = y1 + ua*(y2-y1) return (int(x), int(y)) return None while True: img = sensor.snapshot() # 中值滤波去噪(引用[2]) img.median(1) # 检测三角形 triangles = detect_triangles(img) for tri in triangles: p1, p2, p3 = tri img.draw_line(p1[0], p1[1], p2[0], p2[1], color=255) img.draw_line(p2[0], p2[1], p3[0], p3[1], color=255) img.draw_line(p3[0], p3[1], p1[0], p1[1], color=255) # 计算中心点 cx = (p1[0] + p2[0] + p3[0]) // 3 cy = (p1[1] + p2[1] + p3[1]) // 3 img.draw_cross(cx, cy, color=255, size=10) def region_growing(img, seed): """区域生长算法""" directions = [(0,1), (1,0), (0,-1), (-1,0)] region = [] stack = [seed] while stack: x, y = stack.pop() if (x, y) not in region: region.append((x, y)) for dx, dy in directions: nx, ny = x+dx, y+dy if 0 <= nx < img.width() and 0 <= ny < img.height(): # 相似性判断(灰度值接近) if abs(img.get_pixel(x,y) - img.get_pixel(nx,ny)) < 10: stack.append((nx, ny)) return region def analyze_region(region): """分析区域形状特征""" xs = [p[0] for p in region] ys = [p[1] for p in region] min_x, max_x = min(xs), max(xs) min_y, max_y = min(ys), max(ys) # 计算宽高比 w, h = max_x - min_x, max_y - min_y aspect_ratio = w / h if h != 0 else 0 # 计算面积与边界框面积area = len(region) bbox_area = w * h density = area / bbox_area if bbox_area > 0 else 0 # 三角形特征:0.4 < density < 0.6, 0.7 < aspect_ratio < 1.3 if 0.4 < density < 0.6 and 0.7 < aspect_ratio < 1.3: return True return False # 在主循环中使用 while True: img = sensor.snapshot() img.median(1) # 中值滤波 # 采样种子点(实际应用中需要更智能的种子选择) seeds = [(img.width()//4, img.height()//4), (3*img.width()//4, img.height()//4), (img.width()//4, 3*img.height()//4), (3*img.width()//4, 3*img.height()//4)] for seed in seeds: region = region_growing(img, seed) if len(region) > 100 and analyze_region(region): # 过滤小区域 # 绘制区域边界 for x, y in region: img.set_pixel(x, y, 255) # 创建三角形模板 template = image.Image(30, 30, sensor.GRAYSCALE) # 绘制三角形 for i in range(15): template.draw_line(15-i, 15+i, 15+i, 15+i, color=255) template.draw_line(0, 29, 29, 29, color=255) # 在主循环中使用模板匹配 while True: img = sensor.snapshot() img.median(1) # 模板匹配 result = img.find_template(template, 0.7, step=4, search=image.SEARCH_EX) if result: img.draw_rectangle(result) img.draw_string(result[0], result[1], "Triangle", color=255) 此代码能识别三角形,但误差有点大,希望能识别黑色形状三角形,且只显示黑色三角形
08-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值