Count nodes in each subtree - recursion

I need to solve a bigger algorithm and one of the steps is count nodes in each subtree
I dont need the code to do it but I need help to understand
The exercise is like this:
basically i need to return a new tree , each node containing the value of the node , and the number of elements in the left subtree and number of elements in the right subtree.
this is the method
public AB NumberOnEachSubtree(NodeAB a,NodeAB b) {
}
i think i can make the subtree in the first line of code and then add each node as I go trough the orignal tree, when you come back in recursion count number of nodes
but I dont have idea how to do it..
help
each node has left node and right node and numberNodesLeft and numberNodesRight

Here is a solution in JAVA. Basically, create a TreeNode class that includes number of left Nodes and number of right Nodes. I realize this answer is probably too late for OP but hope it will help someone in the long run.
class TreeNode{
TreeNode left;
TreeNode right;
int leftNodes;
int rightNodes;
int value;
public TreeNode(int value){
value=value;
TreeNode left = null;
TreeNode right = null;
leftNodes =rightNodes=0;
}
}
public void numofRightLeftSubTree(TreeNode root){
numNodes(root);
System.out.println("number of left tree nodes are " + root.leftNodes );
System.out.println("number of right tree nodes are " + root.rightNodes);
}
public int numNodes(TreeNode root) {
if (root == null) return 0;
int left = numNodes(root.left);
int right = numNodes(root.right);
root.leftNodes = left;
root.rightNodes = right;
return left + right + 1;
}

I can give you a pseudocode of the algorithm:
class TreeNode
{
integer CountLeftChildren()
{
integer count = 0
if (hasLeftChildren)
{
foreach(child in LeftChildren)
{
count++
child+=child.CountLeftChildren()
child+=child.CountRightChildren()
}
}
return count
}
integer CountRightChildren()
{
integer count = 0
if (hasRightChildren)
{
foreach(child in RightChildren)
{
count++
child+=child.CountLeftChildren()
child+=child.CountRightChildren()
}
}
return count
}
}
Hope it helps...

Here is a solution in Haskell, since it is so concise you should be able to figure out the algorithm's steps, even if not familiar with the language.
A suitable tree data type:
data Tree a = Nil
| Leaf a
| Br a (Tree a) (Tree a) deriving Show
Your example tree from the picture:
t = Br 3 (Br 5 Nil (Leaf 9))
(Br 8 (Leaf 1) Nil)
The recursive function, transforming a tree with Integer nodes into a tree with triples of Integers as nodes. The recursive solutions are in tl and tr for the left and right subtree, and the count function counts the nodes of a transformed (sub)tree.
transform :: Tree Integer -> Tree (Integer, Integer, Integer)
transform Nil = Nil
transform (Leaf a) = Leaf (0, a, 0)
transform (Br a l r) = (Br (count tl, a, count tr) tl tr)
where tl = transform l
tr = transform r
count Nil = 0
count (Leaf a) = 1
count (Br a l r) = count l + count r + 1
If you save the above code in a .hs file and try it in a Haskell interpreter, you can play with it. In the interpreter hugs:
Main> t
Br 3 (Br 5 Nil (Leaf 9)) (Br 8 (Leaf 1) Nil)
Main> transform t
Br (2,3,2) (Br (0,5,1) Nil (Leaf (0,9,0))) (Br (1,8,0) (Leaf (0,1,0)) Nil)
I hope this helps you developing the right solution in your language of choice.

Related

How to “tripartite” a tree using 0, 1 and 2 and maximize the numbers used?

An interesting problem is to assign labels (0, 1 or 2) for every node in a tree (not necessarily binary), where no parent-child pair can have the same label. In addition, we need to maximize the sum of all labels, i.e., use as little 0 as possible. Return the minimum number of 0 labels used. Some leaf nodes have been pre-labeled. We cannot change those labels. If there are no way to assign labels, for example, one parent node has children pre-labeled with all three labels, return negative infinity.
I am trying dynamic programming on this. One possible recurrence is that OPT(v) returns the number of 0 used to label v’s subtree, and we start at the overall root. When recurse down the tree, try to label each v’s children 0, 1 and 2 (by manipulating v.label field in each node) and see which option returns the minimum number of 0. If we reach bottom and a leaf node has been pre-labeled, we can’t explore all labels but to use the given label. If the leaf node is not pre-labeled, try each label, same as above. The tree itself can be used as my memorization structure where the label is stored in each node’s .label field. But I am not sure how to write the recurrence explicitly, especially for the recursive case when I explore all possible labels for every child of current node. I have no idea to express this combination and get the minimum of it. The base case is fairly simple, perhaps return 1 if the leaf is labeled 0 and return 0 otherwise.
Your idea looks fine. Just one thing to improve: the memoization should concern not just one label value, but possibly all 3 label values (0, 1 and 2). For each label you would (per node) memoize what the minimum number of zeroes is in that node's tree (where it is the root) when that label is assigned to it.
Then, depending on which choice you made for the parent node, you would look at the two possible labels that remain and choose the label which has the least number of zeroes linked to it.
For the below implementation I have used this tree as example:
*
/ \
* * ___
/|\ / \ \
1 * * 2 * *
/ \ \
* 2 2
/|\
2 * 0
The asterisks are nodes that have no label.
So the algorithm would start at the root and temporarily assign it a 0, then see what effect and possibilities that leaves for the children. Then for each child go through the possible values it can have (not zero), ...and recurse deeper into the tree, each time backtracking -- registering the count of 0 labels -- and continuing with the next possible label for the node (and going down the tree again unless memoization is available).
For the above example we can see that an optimal labeling would be:
0
/ \
2 1 ___
/|\ / \ \
1 1 1 2 0 0
/ \ \
1 2 2
/|\
2 2 0
The root and its left child could swap values -- it doesn't matter. The result is 4 zeroes.
Here is the implementation:
// Main algorithm:
function triple(node, parentLabel=-1) {
let choices = node.label !== undefined ? [node.label] : [0,1,2];
let minCount = Infinity;
for (let label of choices) {
if (label === parentLabel) continue; // We cannot use same label as parent has
let count = node.memo[label]; // Already memoized?
if (count === undefined) { // No...
count = 0;
for (let child of node.children) {
count += triple(child, label); // recur
if (count >= minCount) break; // not better...
}
node.memo[label] = count;
}
if (label === 0) count++; // Count the zero
if (count < minCount) minCount = count; // better!
}
// Minimum number of 0-labels if parent has the given parentLabel
return minCount;
}
class Node {
constructor(label, ...children) {
this.label = label;
this.children = children;
this.memo = [undefined, undefined, undefined];
}
}
// Short-cut function for creating a Node instance with or without label
function N(...children) {
let label = undefined;
if (typeof children[0] === "number") { // first argument is a label
label = children.shift(); // extract first argument
}
return new Node(label, ...children);
}
// Demo
let tree = N(
N(
N(1), N(), N()
),
N(
N(2),
N(
N(
N(2), N(), N(0)
),
N(2)
),
N(
N(2)
)
)
)
console.log("input tree:");
console.log(tree);
let count = triple(tree);
console.log("Number of zeroes:", count);
This implementation would return Infinity when there is no valid labelling possible.

Lex && Yacc compiler homework

Hello(my english isn't very well I hope you will understand) , I have a misson to make a compiler, already made the language in the lex and yacc but i'm pretty stuck, our teacher asked from us to build AST tree from the language and print it with pre-order. he gave us example for the text:
function void foo(int x, y, z; real f) {
if (x>y) {
x = x + f;
}
else {
y = x + y + z;
x = f * 2;
z = f;
}
}
the output of the AST tree with pre-order should be:
(CODE
(FUNCTION
foo
(ARGS
(INT x y z)
(REAL f)
)
(TYPE VOID)
(BODY
(IF-ELSE
(> x y)
(BLOCK
(= x
(+ x f)
)
)
(BLOCK
(= y
(+
(+ x y)
z
)
)
(
(= x
(* f 2)
)
(= z f)
)
)
)
)
my question is how should I build the tree? I mean which token will go to left which will go to right so I can get the same output ?
like
makeTree($1,$2,$3);
node,left,right
Help please :)
Stephen Johnson wrote a technical paper to accompany yacc about 42 years ago. Have you read it, and do you understand it?
If yes, a syntax rule like:
expr : expr '+' expr { $$ = node( '+', $1, $3 ); }
node is effectively creating an abstract syntax tree node; and each reduction performed by yacc is the opportunity to build this tree from the bottom up. That is the most important thing to know about yacc; it builds from the bottom up, and you need to construct your data structures likewise.
When the parse is complete ( for whatever version of complete your grammar yields ), the resultant value ($$) is the root of your syntax tree.
followup
You might want to devise a node data structure something like this:
typedef struct Node Node;
typedef struct NodeList NodeList;
struct NodeList {
int Num;
Node *List;
};
struct Node {
int Type;
union {
unsigned u; unsigned long ul; char *s, ... ;
Variable *var;
Node *Expression;
NodeList *List;
} Operands[3];
};
With this you could devise a node of type '+', which defined 2 Operands, corresponding to the Left and Right sides of the '+' opcode.
You could also have a node of type IF, which had three operands:
a conditional Expression
a List of Nodes to perform if the conditional was true
a List of Nodes to perform if the conditional was false.
You could have a node of type Func, which had three operands:
A Type of return value.
A List of arguments.
A List of Nodes comprising the body of the function
I would give more examples but formatting lists with this UI is as much fun as kicking a whale down a beach.

Course Scheduling from Leetcode

This is my solution to Course Scheduling Problem from leetcode. I am looking for any suggestions to improve my code, even slightest ones.
Here is the question:
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1] .
Example 2:
Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
Here is my solution:
class Solution:
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
#Convert prerequisites into an adjacency list
adj = []
for i in range(numCourses):
adj.append(set())
for pair in prerequisites:
adj[pair[0]].add(pair[1])
def DFSHelper(s):
visited.add(s)
stack.add(s)
for neighbor in adj[s]:
# if neighbor vertex has never been visted before, there is no way it could be a backedge.
# visit this unvisited vertex
if(neighbor not in visited):
if(not DFSHelper(neighbor)):
return False
Sorted.append(neighbor)
else:
if(neighbor in stack):
return False
stack.remove(s)
return True
visited = set()
stack = set()
Sorted = []
for j in range(len(adj)):
if(j not in visited):
if(not DFSHelper(j)):
print(j)
return []
Sorted.append(j)
return Sorted
I first converted given prerequisites list into an adjacency list representation of graph, then did topological sorting of the graph. I used DFS recursively to topologically sort the graph. The list Sorted stores the result of sorting. While doing DFS I also checked if the graph contains any cycle, if it does just return []. For purpose of checking cycle I maintained a set called stack that stores all the vertices that are currently in call stack.
This is a simple question first create a graph and then find topological sorting on nodes.
If topological order contains all nodes then we have our answer else not possible to finish all the courses.
class Solution {
public int[] findOrder(int n, int[][] prerequisites) {
List<Integer>[] g = new ArrayList[n];
for(int i = 0; i < n; i++)g[i] = new ArrayList();
int[] deg = new int[n];
for(int[] e: prerequisites) {
g[e[1]].add(e[0]);
deg[e[0]]++;
}
Queue<Integer> q = new LinkedList();
for(int i = 0; i < n; i++) {
if(deg[i] == 0)q.add(i);
}
int[] res = new int[n];
int idx = 0;
while(!q.isEmpty()) {
int u = q.poll();
res[idx++] = u;
for(int v: g[u]) {
deg[v]--;
if(deg[v] == 0) q.add(v);
}
}
return idx == n ? res: new int[0];
}}

iterative version of recursive algorithm to make a binary tree

Given this algorithm, I would like to know if there exists an iterative version. Also, I want to know if the iterative version can be faster.
This some kind of pseudo-python...
the algorithm returns a reference to root of the tree
make_tree(array a)
if len(a) == 0
return None;
node = pick a random point from the array
calculate distances of the point against the others
calculate median of such distances
node.left = make_tree(subset of the array, such that the distance of points is lower to the median of distances)
node.right = make_tree(subset, such the distance is greater or equal to the median)
return node
A recursive function with only one recursive call can usually be turned into a tail-recursive function without too much effort, and then it's trivial to convert it into an iterative function. The canonical example here is factorial:
# naïve recursion
def fac(n):
if n <= 1:
return 1
else:
return n * fac(n - 1)
# tail-recursive with accumulator
def fac(n):
def fac_helper(m, k):
if m <= 1:
return k
else:
return fac_helper(m - 1, m * k)
return fac_helper(n, 1)
# iterative with accumulator
def fac(n):
k = 1
while n > 1:
n, k = n - 1, n * k
return k
However, your case here involves two recursive calls, and unless you significantly rework your algorithm, you need to keep a stack. Managing your own stack may be a little faster than using Python's function call stack, but the added speed and depth will probably not be worth the complexity. The canonical example here would be the Fibonacci sequence:
# naïve recursion
def fib(n):
if n <= 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
# tail-recursive with accumulator and stack
def fib(n):
def fib_helper(m, k, stack):
if m <= 1:
if stack:
m = stack.pop()
return fib_helper(m, k + 1, stack)
else:
return k + 1
else:
stack.append(m - 2)
return fib_helper(m - 1, k, stack)
return fib_helper(n, 0, [])
# iterative with accumulator and stack
def fib(n):
k, stack = 0, []
while 1:
if n <= 1:
k = k + 1
if stack:
n = stack.pop()
else:
break
else:
stack.append(n - 2)
n = n - 1
return k
Now, your case is a lot tougher than this: a simple accumulator will have difficulties expressing a partly-built tree with a pointer to where a subtree needs to be generated. You'll want a zipper -- not easy to implement in a not-really-functional language like Python.
Making an iterative version is simply a matter of using your own stack instead of the normal language call stack. I doubt the iterative version would be faster, as the normal call stack is optimized for this purpose.
The data you're getting is random so the tree can be an arbitrary binary tree. For this case, you can use a threaded binary tree, which can be traversed and built w/o recursion and no stack. The nodes have a flag that indicate if the link is a link to another node or how to get to the "next node".
From http://en.wikipedia.org/wiki/Threaded_binary_tree
Depending on how you define "iterative", there is another solution not mentioned by the previous answers. If "iterative" just means "not subject to a stack overflow exception" (but "allowed to use 'let rec'"), then in a language that supports tail calls, you can write a version using continuations (rather than an "explicit stack"). The F# code below illustrates this. It is similar to your original problem, in that it builds a BST out of an array. If the array is shuffled randomly, the tree is relatively balanced and the recursive version does not create too deep a stack. But turn off shuffling, and the tree gets unbalanced, and the recursive version stack-overflows whereas the iterative-with-continuations version continues along happily.
#light
open System
let printResults = false
let MAX = 20000
let shuffleIt = true
// handy helper function
let rng = new Random(0)
let shuffle (arr : array<'a>) = // '
let n = arr.Length
for x in 1..n do
let i = n-x
let j = rng.Next(i+1)
let tmp = arr.[i]
arr.[i] <- arr.[j]
arr.[j] <- tmp
// Same random array
let sampleArray = Array.init MAX (fun x -> x)
if shuffleIt then
shuffle sampleArray
if printResults then
printfn "Sample array is %A" sampleArray
// Tree type
type Tree =
| Node of int * Tree * Tree
| Leaf
// MakeTree1 is recursive
let rec MakeTree1 (arr : array<int>) lo hi = // [lo,hi)
if lo = hi then
Leaf
else
let pivot = arr.[lo]
// partition
let mutable storeIndex = lo + 1
for i in lo + 1 .. hi - 1 do
if arr.[i] < pivot then
let tmp = arr.[i]
arr.[i] <- arr.[storeIndex]
arr.[storeIndex] <- tmp
storeIndex <- storeIndex + 1
Node(pivot, MakeTree1 arr (lo+1) storeIndex, MakeTree1 arr storeIndex hi)
// MakeTree2 has all tail calls (uses continuations rather than a stack, see
// http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!171.entry
// for more explanation)
let MakeTree2 (arr : array<int>) lo hi = // [lo,hi)
let rec MakeTree2Helper (arr : array<int>) lo hi k =
if lo = hi then
k Leaf
else
let pivot = arr.[lo]
// partition
let storeIndex = ref(lo + 1)
for i in lo + 1 .. hi - 1 do
if arr.[i] < pivot then
let tmp = arr.[i]
arr.[i] <- arr.[!storeIndex]
arr.[!storeIndex] <- tmp
storeIndex := !storeIndex + 1
MakeTree2Helper arr (lo+1) !storeIndex (fun lacc ->
MakeTree2Helper arr !storeIndex hi (fun racc ->
k (Node(pivot,lacc,racc))))
MakeTree2Helper arr lo hi (fun x -> x)
// MakeTree2 never stack overflows
printfn "calling MakeTree2..."
let tree2 = MakeTree2 sampleArray 0 MAX
if printResults then
printfn "MakeTree2 yields"
printfn "%A" tree2
// MakeTree1 might stack overflow
printfn "calling MakeTree1..."
let tree1 = MakeTree1 sampleArray 0 MAX
if printResults then
printfn "MakeTree1 yields"
printfn "%A" tree1
printfn "Trees are equal: %A" (tree1 = tree2)
Yes it is possible to make any recursive algorithm iterative. Implicitly, when you create a recursive algorithm each call places the prior call onto the stack. What you want to do is make the implicit call stack into an explicit one. The iterative version won't necessarily be faster, but you won't have to worry about a stack overflow. (do I get a badge for using the name of the site in my answer?
While it is true in the general sense that directly converting a recursive algorithm into an iterative one will require an explicit stack, there is a specific sub-set of algorithms which render directly in iterative form (without the need for a stack). These renderings may not have the same performance guarantees (iterating over a functional list vs recursive deconstruction), but they do often exist.
Here is stack based iterative solution (Java):
public static Tree builtBSTFromSortedArray(int[] inputArray){
Stack toBeDone=new Stack("sub trees to be created under these nodes");
//initialize start and end
int start=0;
int end=inputArray.length-1;
//keep memoy of the position (in the array) of the previously created node
int previous_end=end;
int previous_start=start;
//Create the result tree
Node root=new Node(inputArray[(start+end)/2]);
Tree result=new Tree(root);
while(root!=null){
System.out.println("Current root="+root.data);
//calculate last middle (last node position using the last start and last end)
int last_mid=(previous_start+previous_end)/2;
//*********** add left node to the previously created node ***********
//calculate new start and new end positions
//end is the previous index position minus 1
end=last_mid-1;
//start will not change for left nodes generation
start=previous_start;
//check if the index exists in the array and add the left node
if (end>=start){
root.left=new Node(inputArray[((start+end)/2)]);
System.out.println("\tCurrent root.left="+root.left.data);
}
else
root.left=null;
//save previous_end value (to be used in right node creation)
int previous_end_bck=previous_end;
//update previous end
previous_end=end;
//*********** add right node to the previously created node ***********
//get the initial value (inside the current iteration) of previous end
end=previous_end_bck;
//start is the previous index position plus one
start=last_mid+1;
//check if the index exists in the array and add the right node
if (start<=end){
root.right=new Node(inputArray[((start+end)/2)]);
System.out.println("\tCurrent root.right="+root.right.data);
//save the created node and its index position (start & end) in the array to toBeDone stack
toBeDone.push(root.right);
toBeDone.push(new Node(start));
toBeDone.push(new Node(end));
}
//*********** update the value of root ***********
if (root.left!=null){
root=root.left;
}
else{
if (toBeDone.top!=null) previous_end=toBeDone.pop().data;
if (toBeDone.top!=null) previous_start=toBeDone.pop().data;
root=toBeDone.pop();
}
}
return result;
}

iterative version of easy recursive algorithm

I have a quite simple question, I think.
I've got this problem, which can be solved very easily with a recursive function, but which I wasn't able to solve iteratively.
Suppose you have any boolean matrix, like:
M:
111011111110
110111111100
001111111101
100111111101
110011111001
111111110011
111111100111
111110001111
I know this is not an ordinary boolean matrix, but it is useful for my example.
You can note there is sort of zero-paths in there...
I want to make a function that receives this matrix and a point where a zero is stored and that transforms every zero in the same area into a 2 (suppose the matrix can store any integer even it is initially boolean)
(just like when you paint a zone in Paint or any image editor)
suppose I call the function with this matrix M and the coordinate of the upper right corner zero, the result would be:
111011111112
110111111122
001111111121
100111111121
110011111221
111111112211
111111122111
111112221111
well, my question is how to do this iteratively...
hope I didn't mess it up too much
Thanks in advance!
Manuel
ps: I'd appreciate if you could show the function in C, S, python, or pseudo-code, please :D
There is a standard technique for converting particular types of recursive algorithms into iterative ones. It is called tail-recursion.
The recursive version of this code would look like (pseudo code - without bounds checking):
paint(cells, i, j) {
if(cells[i][j] == 0) {
cells[i][j] = 2;
paint(cells, i+1, j);
paint(cells, i-1, j);
paint(cells, i, j+1);
paint(cells, i, j-1);
}
}
This is not simple tail recursive (more than one recursive call) so you have to add some sort of stack structure to handle the intermediate memory. One version would look like this (pseudo code, java-esque, again, no bounds checking):
paint(cells, i, j) {
Stack todo = new Stack();
todo.push((i,j))
while(!todo.isEmpty()) {
(r, c) = todo.pop();
if(cells[r][c] == 0) {
cells[r][c] = 2;
todo.push((r+1, c));
todo.push((r-1, c));
todo.push((r, c+1));
todo.push((r, c-1));
}
}
}
Pseudo-code:
Input: Startpoint (x,y), Array[w][h], Fillcolor f
Array[x][y] = f
bool hasChanged = false;
repeat
for every Array[x][y] with value f:
check if the surrounding pixels are 0, if so:
Change them from 0 to f
hasChanged = true
until (not hasChanged)
For this I would use a Stack ou Queue object. This is my pseudo-code (python-like):
stack.push(p0)
while stack.size() > 0:
p = stack.pop()
matrix[p] = 2
for each point in Arround(p):
if matrix[point]==0:
stack.push(point)
The easiest way to convert a recursive function into an iterative function is to utilize the stack data structure to store the data instead of storing it on the call stack by calling recursively.
Pseudo code:
var s = new Stack();
s.Push( /*upper right point*/ );
while not s.Empty:
var p = s.Pop()
m[ p.x ][ p.y ] = 2
s.Push ( /*all surrounding 0 pixels*/ )
Not all recursive algorithms can be translated to an iterative algorithm. Normally only linear algorithms with a single branch can. This means that tree algorithm which have two or more branches and 2d algorithms with more paths are extremely hard to transfer into recursive without using a stack (which is basically cheating).
Example:
Recursive:
listsum: N* -> N
listsum(n) ==
if n=[] then 0
else hd n + listsum(tl n)
Iteration:
listsum: N* -> N
listsum(n) ==
res = 0;
forall i in n do
res = res + i
return res
Recursion:
treesum: Tree -> N
treesum(t) ==
if t=nil then 0
else let (left, node, right) = t in
treesum(left) + node + treesum(right)
Partial iteration (try):
treesum: Tree -> N
treesum(t) ==
res = 0
while t<>nil
let (left, node, right) = t in
res = res + node + treesum(right)
t = left
return res
As you see, there are two paths (left and right). It is possible to turn one of these paths into iteration, but to translate the other into iteration you need to preserve the state which can be done using a stack:
Iteration (with stack):
treesum: Tree -> N
treesum(t) ==
res = 0
stack.push(t)
while not stack.isempty()
t = stack.pop()
while t<>nil
let (left, node, right) = t in
stack.pop(right)
res = res + node + treesum(right)
t = left
return res
This works, but a recursive algorithm is much easier to understand.
If doing it iteratively is more important than performance, I would use the following algorithm:
Set the initial 2
Scan the matrix for finding a 0 near a 2
If such a 0 is found, change it to 2 and restart the scan in step 2.
This is easy to understand and needs no stack, but is very time consuming.
A simple way to do this iteratively is using a queue.
insert starting point into queue
get first element from queue
set to 2
put all neighbors that are still 0 into queue
if queue is not empty jump to 2.

Resources