LeetCode 2579. Count Total Number of Colored Cells(2025/3/5 每日一题)

标题:Count Total Number of Colored Cells

题目:

There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n, indicating that you must do the following routine for n minutes:

  • At the first minute, color any arbitrary unit cell blue.
  • Every minute thereafter, color blue every uncolored cell that touches a blue cell.

Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.

例:

Example 1:

Input: n = 1
Output: 1
Explanation: After 1 minute, there is only 1 blue cell, so we return 1.

Example 2:

Input: n = 2
Output: 5
Explanation: After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. 

Constraints:

  • 1 <= n <= 105

解题思路:这道题虽然是Medium难度,但相对简单,是纯数学题。只要找对思路即可。在一个无限大的二维网格中涂颜色,第一分钟图一个网格,从第二分钟开始,将带颜色网格周边的所有网格都图上颜色,以此类推……我画了个图帮助分析:

画出了前五分钟图了颜色的网格。为区分每一分钟图的网格,我用不同颜色,不同数字标注。可以看出网格成菱形增大。除了第一、二分钟,每一分钟增长都包含两部分:顶点的4个网格(用黑色字体标注),两个顶点中间的两部分(用红色字体标注)。以第5分钟为例,用黑色圈圈出的是顶点,用红色圈圈出的是中间部分。

可以看出:

  • 顶点部分每一分钟都增加4个(第一分钟除外)
  • 中间部分每一分钟增加(n-3)*4个,n代表第n分钟(第一、二分钟除外)

因此将这两部分加和即是最后结果,前n分钟共增加的网格数包含三部分:

  • 第一分钟增加1个
  • 顶点部分共增加 4*(n-1)个
  • 中间部分是等差数列,共增加4 + 8 + 12 + ... + (n - 2) * 4 = \frac{(4 + (n - 2) * 4) * (n - 2)}{2}

代码如下:

class Solution {
public:
    long long coloredCells(int n) {
        long long ln = (long long) n;
        return 1 + 4 * (ln - 1) + (2 + (ln - 2) * 2) * (ln - 2);
    }
};

Memeory是为什么?明明没占更多的Memeory呀T_T

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值