BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Computer vision34 of 35 in topic

830. Fill a matrix along zigzag diagonals

MediumComputer vision Pro

Image codecs such as JPEG read an 8 by 8 block of coefficients in a zigzag order along anti-diagonals so that low frequencies come first. This exercise builds that order.

Write zigzag_fill(rows, cols). Return a rows by cols matrix (a list of lists) filled with 1, 2, 3, ... in zigzag order. Start at the top-left cell. Walk anti-diagonal 0, then 1, then 2, and so on, where anti-diagonal d holds cells with row + col == d. On even d move up and to the right (row decreasing); on odd d move down and to the left (row increasing).

Functiondef zigzag_fill(rows, cols)

Example 1

Input: zigzag_fill(3, 3)

Output: [[1, 2, 6], [3, 5, 7], [4, 8, 9]]

Example 2

Input: zigzag_fill(1, 4)

Output: [[1, 2, 3, 4]]

Constraints

  • 1 <= rows, cols <= 500
Hint 1

Name the diagonal by row + col.

Hint 2

Clamp the row range per diagonal.

Hint 3

Flip direction by parity of d.

Common mistakes
  • Simulating moves and bouncing off edges with many special cases.
  • Getting the parity backwards so the second cell is below the first.
  • Assuming the matrix is square.
Understand the idea

Index arithmetic on anti-diagonals replaces a fiddly direction-switching walk. In a 3 by 3 grid, diagonal 2 holds (2, 0), (1, 1), (0, 2); because 2 is even it is walked from row 2 up to row 0, so those cells get 4, 5, 6. The approach is O(rows x cols) and handles any rectangle.

Topics
Computer vision
Similar questions
  • Max pooling forward and backwardMedium
  • Detect edges with Sobel filters and a magnitude thresholdMedium
  • Unfold image patches with im2colMedium
  • Resize an image with bilinear interpolationMedium
All Computer vision problems
Report
830 / 903
Python 3solution.pyPython idle
1
2
3
4
def zigzag_fill(rows, cols):
# return a rows x cols matrix filled in zigzag diagonal order
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS