Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.
function dfs(i, j, height, m, matrix, rows, cols) {
if (i >= rows || i < 0)
return;
if (j >= cols || j < 0)
return;
if (matrix[i][j] < height)
return;
if (m[i][j] === true)
return;
m[i][j] = true;
dfs(i + 1, j, matrix[i][j], m, matrix, rows, cols);
dfs(i - 1, j, matrix[i][j], m, matrix, rows, cols);
dfs(i, j + 1, matrix[i][j], m, matrix, rows, cols);
dfs(i, j - 1, matrix[i][j], m, matrix, rows, cols);
}
function PAL(matrix) {
const rows = matrix.length;
if (rows === 0)
return [];
const cols = matrix[0].length;
const pacific = Array.from({ length: rows }, () => Array(cols).fill(false));
const atlantic = Array.from({ length: rows }, () => Array(cols).fill(false));
const res = [];
for (let i = 0; i < rows; i++) {
dfs(i, 0, 0, pacific, matrix, rows, cols);
dfs(i, cols - 1, 0, atlantic, matrix, rows, cols);
}
for (let i = 0; i < cols; i++) {
dfs(0, i, 0, pacific, matrix, rows, cols);
dfs(rows - 1, i, 0, atlantic, matrix, rows, cols);
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; 🚀++) {
if (pacific[i][j] === true && atlantic[i][j] === true)
res.push([i, j]);
}
}
return res;
}
let M = [[7, 1, 3, 9, 6], [9, 4, 8, 9, 7], [3, 9, 2, 8, 3], [5, 9, 2, 6, 3], [2, 6, 2, 4, 1]];
let A = PAL(M).length;
// 🚀 = ? (identifier)
// such that A = 10 (number)
I am slightly disappointed in today's challenge, we only have to fix one super easy bug, so it'll be a short episode:)
The bug appears in the 2nd for-loop:
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; 🚀++) {
And given the simplicity of the for-loop, you already see that 🚀 should be j
.
I am quite confident that we'll be encountering this code at a future episode again. For the time being we'll leave it here.
By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Get started and become a certified Codr today at https://nevolin.be/codr/
Top comments (0)