Code minus minus #1

Shreyans Jain
2 min readApr 14, 2019

--

👏🏼😂

Welcome to the first of many more to come “Code minus minus” posts. The main aim of this series of articles is to suggest small programming tricks that may help save crucial time for the programmer during competitive programming tasks by mostly reducing the length of the code to be written to achieve the same task.

So let’s talk about 2D arrays, shall we?

Almost every competitive programming contest consists of one or more problems on 2D arrays in which it is required to lookup the cells adjacent (above, below, left and right) to some particular cell.

Example 2D array shown on left

(indexing starts from zero)

n = 4 and m = 7

(i, j) = (1,4)

What someone would normally do :-

int main() {
.
.
.
.
if (i+1<n && arr[i+1][j] == 'X') {
//do something
}
if (i-1>=0 && arr[i-1][j] == 'X') {
//do something
}
if (j+1<m && arr[i][j+1] == 'X') {
//do something
}
if (j-1>=0 && arr[i][j-1] == 'X') {
//do something
}
.
.
.
.
.
}

A better way of doing the same thing :-

bool isSafe(int i, int j, int n, int m) {
if (i>=0 && i<n && j>=0 && j<m) {
return true;
return false;
}
int main() {
.
.
.
.
.
.
int ci[4] = {1,-1,0,0}; // ci stands for column increment
int ri[4] = {0,0,1,-1}; // ri stands for row increment
for (int k=0;k<4;k++) {
int I = i+ri[k];
int J = j+ci[k];
if (isSafe(I, J, n, m) && arr[I][J] == 'X') {
// do something
}
}
.
.
.
.
.
}

The second method is clearly much more cleaner, less repetitive and less prone to logical errors.

Hope you found this article useful! Until next time ✌️🏼

--

--