DMITRII’s Substack

Share this post

Leetcode daily # 10.05.2023

dmitriisamoilenko.substack.com

Leetcode daily # 10.05.2023

[59. Spiral Matrix II]

DMITRII SAMOILENKO
May 10, 2023
Share

10.05.2023

59. Spiral Matrix II medium

fun generateMatrix(n: Int): Array<IntArray> = Array(n) { IntArray(n) }.apply {
    var dir = 0
    var dxdy = arrayOf(0, 1, 0, -1)
    var x = 0
    var y = 0
    val nextX = { x + dxdy[(dir + 1) % 4] }
    val nextY = { y + dxdy[dir] }
    val valid = { x: Int, y: Int -> x in 0..n-1 && y in 0..n-1 && this[y][x] == 0 }

    repeat (n * n) {
        this[y][x] = it + 1
        if (!valid(nextX(), nextY())) dir = (dir + 1) % 4
        x = nextX()
        y = nextY()
    }
}

blog post

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/208

Intuition

Just implement what is asked. Let’s have the strategy of a robot: move it in one direction until it hits a wall, then change the direction.

Approach

  • to detect an empty cell, we can check it for == 0

Complexity

  • Time complexity:
    O(n2)

  • Space complexity:
    O(n2)

Thanks for reading DMITRII’s Substack! Subscribe for free to receive new posts and support my work.

Share
Previous
Next
Comments
Top
New

No posts

Ready for more?

© 2023 DMITRII SAMOILENKO
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing