Even Tree [HackerRank]

Hi all, I’m sorry about not posting very frequently – thankfully, however, my exams will be coming to a close in the next two weeks, so I will be able to return to regular posting soon.

If you are unfamiliar with graph theory, I recommend that you read my previous post on the subject – it gives an introduction into the topic and the ways in which it appears in competitive programming.

Today, we will solve a relatively simple problem on graph theory which can be found on the ‘HackerRank’ website – given a tree (a graph with no cycles and where any node can be reached from any other node) of N nodes numbered from 1 (which is the root node) to N, our program must find the maximum number of edges it can remove from this tree to obtain a set of trees (commonly called a ‘forest’) where every tree has an even number of nodes.

The source code of my final solution to this problem can be found here.

The problem statement states that it is always possible to remove edges from the main tree to create a forest consisting of only trees with even numbers of nodes, so we do not need to concern ourselves with difficult edge cases. This brings us to a relatively simple solution: any ‘subtree’ (a smaller tree which is part of the main tree – it may have its own root separate from the main root) with an even number of nodes can be separated from the node connecting to its root – therefore, the maximum number of edges which can be removed from the tree to satisfy the problem statement is equal to the number of subtrees with even numbers of nodes. We have now reduced the problem to counting the number of nodes in each subtree.

Our first course of action is to devise a method for storing the tree – the technique I used is known as an ‘adjacency list’. In C++, this is essentially a vector where each element represents a node. For simple graphs like the ones used in this problem, each node can be represented by a vector of integers, with each integer representing a node which can be reached from the node represented by the vector itself. Initially our adjacency list will be empty, however, we will fill it by taking each edge from input as two integers (which represent the two nodes connected by the edge in question) connecting the deeper of the two nodes to the node closer to the root (not vice-versa! The edges in our list only need to be unidirectional).


After creating the adjacency list, we can write a function which performs a depth-first traversal of the tree, counting the number of nodes in each subtree by travelling to each node in turn and counting the number of children it has and adding 1 to this value (this addition represents the current node, which acts as the root). We can do this elegantly using recursion – the numbers of nodes in the subtrees rooted at the deepest points of the tree are always 1 (as these nodes have no child nodes). By this logic, we can have our recurring function return 1 when it reaches a node with no child nodes, and in order to calculate the numbers of nodes in the other subtrees, we recur for every child node of each potential root node and save the sum of the results.


Once we have calculated the number of nodes in every possible subtree of the main tree, we can just iterate through our results and increment our final answer by 1 every time we find a subtree with an even number of nodes. Once this process is complete, we can print out our final value.


Graph Theory – Breadth-first Traversal and Depth-first Traversal

Hello all – given that myself and many other students worldwide are currently in the midst of the exam season, I haven’t been very active on this blog. I hope that you all will bear with me for the time being – when my exams are complete, I will be able to start making blog posts more frequently again.

As the title suggests, this post will be about graph theory, a very interesting and useful aspect of mathematics and computer science which is also encountered frequently in competitive programming. The graphs which we will encounter in this post are not the graphs one may associate with high school statistics! Instead, these graphs consist of a series of ‘nodes’ (sometimes called ‘vertices’), connected by ‘edges’.


These graphs are commonly used to represent a set of points in space, and the connections between them. For example, a problem encountered in a programming contest may involve a set of towns connected by roads – these towns can be represented by graph nodes, and the roads can be represented by the edges in between the nodes. Edges in a graph can be both ‘directed’ and ‘undirected’. To illustrate this concept, we can think of two nodes x and y – if the edge between them is undirected, x can be reached from and y and be reached from x. On the other hand, if the edge is directed, only one of the two nodes can be reached from the other node (if we refer back to the analogy with towns and roads, a directed edge could represent a one-way street).

There are various ways of representing graphs in code, however, we will focus on using an ‘adjacency list’. This is a method of storing a graph by representing each node as a set of edges to other nodes – for example, in C++, an adjacency list could be a vector of vectors of integers, where each vector of integers holds the indices of all of the nodes connected to the node represented by the vector in question. Moreover, if the edges of the graph are undirected, the vectors representing two connected nodes would contain the indices of each other (that is, if the two nodes were x and ythe vector representing x would contain the index of the vector representing y, and vice versa). In the programs used in this post, we will construct our graph by first taking the number of nodes as input, and then taking the number of edges. For each edge, we take two integers – these integers represent the indices of the two nodes connected by an edge.


Many problems in programming contests require graphs to be ‘traversed’ through – this means that the problem’s answer will need to be obtained by moving through a generated graph. Two methods of traversing through graphs will be discussed in this post: depth-first traversal and breadth-first traversal. When these methods are applied in a program, the nodes of a graph are ‘visited’ in a certain sequence determined by the traversal technique. When we say that we have visited a node, we mean that we have obtained its index. An undirected graph will be used in our demonstrations – we will move through this graph and print the index of each node as we visit them.

The depth-first traversal technique moves through a graph in the manner suggested by the name – it goes ‘deep’ into the graph before looking at adjacent routes. The image below shows every node in a graph being traversed using a depth-first traversal starting at the node with an index of 0 (note that we could have started the traversal at any node).


A simple way of implementing a depth-first traversal is through recursion – if we represent the graph as a vector of vectors of integers, we first call a recurring function and pass it the index of the starting node as an argument. Then, we recur for every integer in the vector indexed by the function’s argument (since each integer in this vector represents the index of a node connected to the current node). In order to prevent our traversal algorithm from continuously revisiting the same sets of nodes (this could potentially cause a stack overflow), we can use an array of boolean variables which represents the ‘state’ of each node (that is, whether each node has been visited or not). If the boolean at index i of this array is set to true, then the node at index i of the adjacency list has been visited. Every time we are about to recur, we check to ensure that the index we are about to recur with has not already been visited. Furthermore, every time we recur, we mark the newly-visited node as visited by changing its corresponding boolean value in the array.

An implementation of a depth-first traversal using recursion can be found here.

Alternatively, we can also implement a depth-first traversal in C++ using a stack of integers (these integers represent the indices of the graph nodes) – the main operations we are concerned with here are the ‘push’, ‘top’ and ‘pop’ operations. A stack is a data structure which is available in the C++ – it can be used to store and retrieve variables in the same manner objects can be stored and retrieved from a stack in real life. If we imagine our stack as a stack of sheets of paper, the ‘push’ operation adds a sheet of paper to the top of the stack, the ‘top’ operation retrieves the sheet of paper which is currently at the top of and the ‘pop’ operation removes the sheet of paper which is currently at the top.


To perform a depth-first-traversal using a stack in C++, we initially push the index of the starting node onto the stack. Then, we use a ‘while’ loop which runs as long as the stack contains some integers. Every time we run an iteration of this loop, we use the ‘top’ operation to retrieve the index at the top of the stack (clearly, this index would be the newest index which has been pushed) and then the ‘pop’ operation to remove this index from the top. Then, we loop through all of the connecting indices at this index of the adjacency list and push them onto the stack where appropriate. Note that we still should use an array of boolean variables here – we need to check this array before pushing any indices onto the stack in order to ensure that we do not revisit any previously-visited nodes. Since we are using this array, we will eventually reach a point in the algorithm where we stop pushing any new indices, and we will thus empty the stack and finish the traversal.

An implementation of a depth-first traversal using a stack can be found here.

A breadth-first traversal works in a different manner to a depth-first traversal – here, we check every adjacent node in turn before moving onto the next level of depth (hence why the technique is referred to as breadth-first).


An elegant way to program a breadth-first traversal in C++ is to use a queue – this data structure is vaguely similar to the stack structure in terms of usage, however, we can think of a queue structure as an actual queue of people in real life (as opposed to a stack of papers). Instead of having a ‘top’ operation, we have a ‘front’ operation (which retrieves the person at the front of the queue). Moreover, the ‘pop’ operation removes the person at the front of the queue. Pieces of data can thus be retrieved from a queue in the order they were added – therefore, we can use a ‘while’ loop to program a breadth-first traversal in the same way we use this loop to perform a depth-first traversal. We can begin by pushing the starting node index onto a queue and then pushing each of the nodes connecting to it onto the queue in turn (while still ensuring that we do not revisit previously-visited nodes by checking and updating an array of boolean variables) – this process can be repeated in the loop until there is nothing left to push onto the queue and we run out of nodes which need to be visited. Since the node indices are retrieved from the queue in the order they were pushed, all nodes adjacent to a given node are visited before the other nodes connected to each adjacent node are visited.

An implementation of a breadth-first traversal using a queue can be found here.

That concludes this post! In future posts, we will work through some graph-related problems on competitive programming websites, in addition to continuing the ‘Tetris for Android’ project.

Tetris for Android in the Unity Engine – Part 3 (Tetrominoes)

Good day all – in this post, we will incorporate full ‘tetrominoes’ (shapes consisting of multiple squares) into our mobile ‘Tetris’ game. We have already finished implementing much of the functionality which does this, however, some of the code which was used to power the grid system when only single blocks were used will need to be rewritten in order to accommodate the more complex shapes. Additionally, we will also extend the code which moves the blocks sideways such that a tetromino will only be moved if there are no other fixed blocks in the path.

The final product of this post can be downloaded here.

Staying true to the original Tetris, our version will use the same tetromino shapes which the classic version used – as shown below:


In order to create these tetromino objects, we first need to create the ‘materials’ – these are Unity’s method of storing the ways 2D graphics are mapped onto 3D objects (note that we are using 3D cubes in our game, and they are made to appear 2D by the camera’s orthographic projection). In this case, creating the required materials is relatively simple, as each tetromino is a single solid colour. To create a new material, right-click the project directory, move to the ‘create’ drop-down menu and choose the ‘material’ option. This new material’s properties will then appear the in the inspector tab – from here, we switch the material’s type to ‘Unlit/Color’. We can then select the colour of the material using a hue/saturation grid by clicking on the sole ‘main colour option’. There are seven different tetromino colours used in the original Tetris, so we will create seven different materials.


Now that we have created the required materials, we can use the Unity editor to construct the actual tetromino prefabs – this can be done by dragging a copy of the ‘SingleBlock’ prefab created in the previous post into the scene tab, duplicating it to make multiple separate blocks and then using the level editing tools to create the desired shape. A material can then be dragged from the project tab onto a block in the scene view in order for the material to be applied to the block. The Unity editor boasts a useful feature called ‘vertex snapping’ – if the ‘V’ key is held, a vertex on a single game object can be selected, and then dragged onto a vertex of another object such that the two vertices occupy the same position in the world space. This feature can thus be used to position two cubes next to each other perfectly.

The level-editing features built into the Unity engine can be used to build replicas of every possible tetromino shape present in the original game (we only need to build a tetromino for every single colour we intend to use, as we will implement a block rotation mechanic later on). In order to convert a group of blocks into a single tetromino, select all of the blocks from a tetromino except one in the hierarchy and then drag the selected blocks onto the unselected block (effectively making the unselected block the ‘parent’ of the selected blocks). The model in the hierarchy will then appear as follows:


The parent block of a tetromino can then be dragged into the project tab in order for a prefab to be created.

Once we have created the tetromino prefabs, we will need to alter the code we wrote in the previous posts such that it accommodates shapes consisting of multiple blocks. In the last post, we designed our ‘Tick ()’ function such that it processed every single falling block from a list of all falling blocks – so our first course of action now will be to create a new script for our tetromino models. This script should get attached to the parent blocks (as this makes accessing the child blocks relatively simple). In the ‘Start ()’ function of this script (the function which gets called as the object is instantiated), we first obtain access to the ‘MainControl’ script which we wrote in earlier posts. We also save every single block of the tetromino in question into a list of GameObjects using a ‘while’ loop – as each block is saved, it has its initial position saved into the grid array and is separated from the parent block.

Given the manner in which the ‘Tick ()’ function works (it iterates through a list of moving blocks and processes the movement of each block in turn), it is necessary for us to ensure that the blocks saved in the list of moving blocks are ordered by their positions along the axis, with the lowest blocks saved into the lowest array indices. This is because the ‘Tick ()’ functions sets the grid value referenced by a given object’s current position to ‘null’ (which effectively states that the variable references nothing) before moving the block downwards and updating the grid value referenced by the block’s new position. Therefore, if the blocks at the top of a tetromino (that is, a group of moving blocks) had their movement processed first, there is a high risk of their corresponding grid values being incorrectly reset to ‘null’ when the lower blocks are processed (since all blocks are moved downwards, this is guaranteed to happen if one block is one unit above another block, and is moved downwards first). This would cause blocks to appear to ‘fall through’ other blocks, since the values stored in the grid array are not representative of what is actually being shown on the screen. We can avoid this issue by making sure that the list of moving blocks in MainControl is always sorted appropriately. Since tetrominoes are relatively small – that is, they only consist of several block objects each, a simple selection sorting algorithm can be used to create a new, sorted list in the script attached to a tetromino’s parent block. Moreover, since this script has access to MainControl, the value of the list of moving blocks in MainControl can be directly assigned to the sorted list in the tetromino script.

One of the other issues which has cropped up as a result of multiple blocks falling at the same time is related to the check performed during every ‘Tick ()’ call – every time the function is executed, each block in the falling block list is checked to ensure if there are any blocks under it. If this is the case, all of the blocks in the list are frozen in place and the list is cleared. This logic allows falling squares to be stacked on top of each other, however, the tetromino models do contain blocks already positioned on top of each other (for instance, the square tetromino has two rows of blocks on top of each other, with the rows containing two blocks each). The problem here is that this code causes tetrominoes to become frozen while still falling (as the stacks of blocks in the tetrominoes causes the check mentioned earlier to return true). In order to remedy this, the algorithm must be able to distinguish between blocks with are part of the current falling tetromino, and blocks which have already fallen and are already frozen in place. This can be done using Unity’s ‘tag’ system, which allows us to give each GameObject in the world a string property which can be referenced within the code. In order to create a tag, we select the GameObject, open the tag menu from the inspector window, type in the string value of the new tag and then assign this tag value to the tag of the selected GameObject. The object’s tag can then be accessed within the code using ‘gameObject.tag’ – in our solution, we can create two tags: one which states that a block is moving and another which states that a block is frozen. Newly created tetrominoes should, by default, have all of their blocks use the ‘moving’ tag (so we need to assign this tag value to every block in every tetromino prefab. Furthermore, tetrominoes which have had their falls halted will have all of their blocks’ tag values switched to the ‘frozen’ tag. The screenshot below shows the ‘tag’ menu of a block in the yellow tetromino prefab – notice that it has already had its tag value set to ‘moving’:


The following screenshot shows how the mentioned fix has been implemented in the code:


Another problem which we must tackle is accounting for the varying sizes of each tetromino object (since we are no longer working with 1×1 blocks, we run a risk of having out-of-bounds errors occur when we reference grid positions, if a tetromino is instantiated and positioned on the edges of the grid). this has been done by ensuring that the tetrominoes are not instantiated on the top row, and saving the width of each individual shape so that the value can be used to pick a suitable set of columns for each newly created set of blocks. In order to instantiate a tetromino instead of a single block, we can save all of the tetromino prefabs into an array (using the inspector) and then use ‘Random.Range ()’ to pseudo-randomly select a prefab to clone.



The following images are of the final tetromino prefab script, and the changes to the block instantiation mechanics:



It is possible for the player to create an excessive number of falling tetrominoes through aggressively hitting the ‘speed up time’ button immediately after a new tetromino is created. In order to ensure that each newly created tetromino has an opportunity to be passed through the ‘Tick ()’ function at least once, we can introduce a boolean flag which is checked whenever we attempt to create a new set of falling blocks, and is reset whenever we perform a full ‘Tick ()’ with the current set.

This slideshow requires JavaScript.

Finally, we will edit the functions used to move tetrominoes left and right such that they do not cause the falling blocks to move if other blocks are in the way (in the last post, the functions only prevented movement if the blocks were on the edges of the grid). This is done relatively easily – we can check the values of the cells immediately to the left of right of each falling block, and if these values are not null (that is, a block is already in that grid cell), then the function returns without the blocks being moved.


We have made great strides on this project! In the next post, we will implement the tetromino rotation mechanic.





Tetris for Android in the Unity Engine – Part 2 (Player Input)

Hello all – this is the second part of the series of posts in which I have been developing the video game ‘Tetris’ for the Android platform using the ‘Unity’ engine. In this post, we will enable the player to move the falling blocks from left to right using buttons on the HUD (head-up display). Additionally, we will also implement a feature which enables the player to increase the rate of time and cause the falling blocks to fall faster – this feature is present in many other versions of the game.

The final product of this post of this post can be downloaded here.

In order to allow the player to give input, we need to add three buttons to the user interface – Unity has a UI development toolkit which allows us to do this relatively easily. In Unity, UI objects can be treated as actual GameObjects which are children of a ‘Canvas’ object – these UI objects contain certain components which allow them to function as various different interface elements (such as buttons, sliders and toggles). We need to add a ‘move block left’ button, a ‘move block right’ button and a ‘speed up time’ button – this can be done within the editor. Since the buttons are treated as GameObjects, they can be moved and shaped using the engine’s level editing tools.



Now, we can write the functions which will be called by the engine when the user presses the buttons. The ‘move left’ and ‘move right’ buttons only need to provide a response to tap actions – on the other hand, the ‘speed up time’ button must react to both being pressed and being released. First, we will write the functions called when the left/right movement buttons are pressed. The code which moves the tetrominoes downwards can be copied and edited slightly in order to provide functionality for moving them sideways – instead of looping through each block in the current tetromino and moving it down one row, we can loop through each block and move it either one column to the left or one column to the right. However, before moving any blocks, we need to loop through the entire tetromino and ensure that it is not already positioned on the very edge of the screen (we can do this by checking if any of its blocks are on the very left column or the very right column). If this check is passed, each block in the current tetromino can then be translated by one unit – the grid array which we created in the previous post must be updated in order to reflect this chance. The functions are have been made public in order for them to be called through UI input events.


In order to hook these public functions to their buttons, we set the ‘On Click ()’ option on the ‘Button’ components of the UI button objects which we added to the scene earlier.


Now, if the user presses the ‘move left’ button, the tetromino which is currently falling gets translated one column to the left, and if the user presses the ‘move right’ button, the tetromino which is currently falling gets translated one column to the right.

To speed up the falling block, the player must hold down the ‘speed up time’ button. Therefore, we need to implement two separate functions – one which reacts to the button being initially pressed down (this is where the button starts getting held down) and another which reacts to the button being released (where the button is no longer being held down). By default, the ‘Tick ()’ function which controls the falling tetrominoes is called once per second – in order to speed up the falling blocks, we cancel this pattern using the function ‘CancelInvoke ()’ and then use ‘InvokeRepeating ()’ in order to create a new calling pattern for the ‘Tick ()’ function with less time in between each call. The second argument to the new ‘InvokeRepeating ()’ call is set to 0.0f – this ensures that the ‘Tick ()’ function is instantly called when the ‘speed up time’ button is pressed (if this argument was not 0.0f, it would theoretically be possible for the player to completely freeze the block in mid-air by repeatedly pressing and releasing the ‘speed up time’ button). The same technique for speeding up the falling blocks is used to slow them down when the button is released – in the second function, we use ‘CancelInvoke ()’ to cancel the faster calling pattern before using ‘InvokeRepeating ()’ to replaced the cancelled pattern with the default calling pattern (which has 1-second intervals in between each tick).


We can then add ‘Event Trigger’ components to the ‘speed up time’ button, in order to hook these two public functions to their corresponding button events.


Now, the player has significantly control over the falling blocks in our version of Tetris – the blocks can be moved to the left, moved to the right, or pushed downwards at a higher speed. In the next post, we will start using the Unity editor to construct actual Tetrominoes (coloured groups of blocks) similar to those found in the original game.