Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS paint code asked in an interview

Tags:

algorithm

I had an interview today and was asked this question!

code the MS Paint program. N*N pixels area. given pixel and color, change color in pixel to desired color and if adjacent pixels are of same color change them too.

i approached it by saying i ll take a n* n array and would check for the pixel given and move to the the adjacent. for example the pixel given is x,y i would first check for the color in x,y in the array and next look for (x+1,y+1),(x+1,y),(x,y+1),(x-1,y),(x-1,y-1)....

but the interviewer was not happy can someone suggest me another way with a better algorithm.. which has better space and time complexity!

like image 687
helpme Avatar asked Mar 01 '12 21:03

helpme


People also ask

How do you explain code in interview?

Do explain what you are writing or typing. Do follow the good coding style (such as using descriptive variable names) and structure your codes well (with functions and classes if they are necessary). Do speak out your understanding about the algorithm, data structures or built-in functions you use.


1 Answers

The interviewer was probably asking for flood-fill, which cannot be done with so simple an approach.

If this is flood-fill, diagonal doesn't count as adjacent.

The simplest flood-fill is a recursive call on each adjacent pixel on the array. Using the simple way on a large grid is very likely to run out of stack.

The right way is to enqueue the starting location, then dequeue, check if pixel color is still source color, and scan left and right filling as you go, and enqueue all pixels above and below. Continue until queue is drained.

like image 82
Joshua Avatar answered Oct 29 '22 21:10

Joshua