Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining value based on adjacent cells in matrix

Tags:

c++

algorithm

Input: a maze represented by an arbitrarily sized matrix of bools. (Out of bounds counts as 0)

00100
00100
01110
11111
01110
00100

Output: a nice looking representation of the maze (neighbourhood gets mapped to a wchar_t):

   ┌─┐
   │1│
  ┌┘1└┐
 ┌┘111└┐
 |11111|
 └┐111┌┘
  └┐1┌┘
   └─┘

Edit: Basically each 0 gets mapped to a 4 bit value representing the wall layout.

My approach and thoughts:

I thought it would be simplest to look at each cell at a time. Then look at it's neighbours to determine what kind of value to put there. Turns out I have 8 boolean inputs (all neighbours), this generates 2^8=256 different scenarios. I don't feel like hard coding them all.

Is there a more elegant way to map the values correctly?

like image 298
Martin Nycander Avatar asked Nov 16 '09 18:11

Martin Nycander


People also ask

How do you find adjacent elements in a matrix?

Adjacent elements are all the elements that share a common side or point i.e., they have a vertical, horizontal or diagonal distance of 1. Explanation: Elements adjacent to arr[1][1] (i.e., 5) are: arr[0][0], arr[0][1], arr[0][2], arr[1][0], arr[1][2], arr[2][0], arr[2][1], and arr[2][2].

What are adjacent cells in a matrix?

A neighborhood matrix identifies the cells around each cell that are considered adjacent. The matrix should have one, and only one, cell with value 0 (the focal cell); at least one cell with value 1 (the adjacent cell(s)); All other cells are not considered adjacent and ignored.


1 Answers

I implemented this in my winning entry for the 2004 IOCCC. I'm sure you'll find the code well documented and easy to follow.

If you just want the answer, as I recall, the approach I took was to calculate a bitmap of occupied cells surrounding each cell, and use that as an index into an array of wall characters (or equivalently, glyphs). If, like my solution, you don't permit diagonal travel, the bitmap is 4 bits long, and thus the array has 2^4=16 elements. If you do permit diagonal travel, you need an 8 bit bitmap, and 256 entries.

like image 114
Nick Johnson Avatar answered Nov 11 '22 05:11

Nick Johnson