Блог пользователя 0-jij-0

Автор 0-jij-0, история, 3 года назад, По-английски

Hello,

I was wondering if there's any trick that allows us to iterate over the boundary of an $$$N \times M$$$ grid using a single loop instead of 4 or 2.

To iterate over the whole grid for example we can iterate from 0 to $$$NM$$$ and have $$$i = x / M$$$ and $$$j = x \% M$$$.

So is there any smart thing like this to do for the boundary only (i.e pairs $$$(i, j)$$$ such that either $$$i = 0$$$ or $$$i = N - 1$$$ or $$$j = 0$$$ or $$$j = M - 1$$$)

Thanks for future help!

EDIT: Problem Solved!

Solution 1
Solution 2
My Solution inspired by the previous one
  • Проголосовать: нравится
  • +20
  • Проголосовать: не нравится

»
2 года назад, # |
Rev. 2   Проголосовать: нравится +4 Проголосовать: не нравится

Here you go

code
»
2 года назад, # |
  Проголосовать: нравится +25 Проголосовать: не нравится

I would probably do it this way:

code

But note that it doesn't work when $$$n = 1$$$ or $$$m = 1$$$ so you will probably have to run a simple loop for that.

  • »
    »
    2 года назад, # ^ |
    Rev. 3   Проголосовать: нравится +3 Проголосовать: не нравится

    I got your point and your idea to skip the stuff in between actually inspired me to get the following and the complexity would be simply $$$O(N + M)$$$

    Code

    Thank you!

»
2 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by 0-jij-0 (previous revision, new revision, compare).