764. Largest Plus Sign

复制代码
package LeetCode_764

/**
 * 764. Largest Plus Sign
 * https://leetcode.com/problems/largest-plus-sign/
 *
 * In a 2D grid from (0, 0) to (N-1, N-1), every cell contains a 1, except those cells in the given list mines which are 0.
 * What is the largest axis-aligned plus sign of 1s contained in the grid? Return the order of the plus sign.
 * If there is none, return 0.
An "axis-aligned plus sign of 1s of order k" has some center grid[x][y] = 1 along with 4 arms of length k-1
going up, down, left, and right, and made of 1s.
This is demonstrated in the diagrams below.
Note that there could be 0s or 1s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1s.

Examples of Axis-Aligned Plus Signs of Order k:

Order 1:
000
010
000

Order 2:
00000
00100
01110
00100
00000

Order 3:
0000000
0001000
0001000
0111110
0001000
0001000
0000000

Example 1:
Input: N = 5, mines = [[4, 2]]
Output: 2
Explanation:
11111
11111
11111
11111
11011
In the above grid, the largest plus sign can only be order 2.  One of them is marked in bold.

Example 2:
Input: N = 2, mines = []
Output: 1
Explanation:
There is no plus sign of order 2, but there is of order 1.

Example 3:
Input: N = 1, mines = [[0, 0]]
Output: 0
Explanation:
There is no plus sign, so return 0.
 * */
class Solution {
    /*
    * solution 1: bruce force, start scan from each 1, than expand its four directions: left, up, right, down,
    * Time:O(n^3), Space:O(n^2)
    * */
    fun orderOfLargestPlusSign(N: Int, mines: Array<IntArray>): Int {
        //init grid
        val grid = Array(N) { IntArray(N) { 1 } }
        //update value in grid to 0 by mines, because mines contains the position that is 0
        for (item in mines) {
            grid[item[0]][item[1]] = 0
        }
        var count = 0
        for (i in 0 until N) {
            for (j in 0 until N) {
                //k represent the step can expand for current 1
                var k = 0
                while (canExpand(grid, N, i, j, k)) {
                    k++
                }
                count = Math.max(count, k)
            }
        }
        return count
    }

    private fun canExpand(grid: Array<IntArray>, N: Int, x: Int, y: Int, k: Int): Boolean {
        if (x - k < 0 || y - k < 0 || x + k >= N || y + k >= N) {
            return false
        }
        return grid[x-k][y]==1 && grid[x+k][y]==1 && grid[x][y-k]==1 && grid[x][y+k]==1
    }
}
复制代码

 

posted @   johnny_zhao  阅读(96)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示