In this article, we explore two essential problem-solving techniques—Lattice Multiplication for fast calculations and a Maze Pathfinding Algorithm to solve grid-based puzzles. These techniques are widely used in competitive programming, interviews, and real-world applications.
A colony of 8 cells is arranged in a straight line. Every day, each cell competes with its neighboring cells. The rules of competition are:
Write a function cellCompete(int* cells, int days)
that takes:
Input: [1,0,0,0,0,1,0,0], 1
Expected Output: [0,1,0,0,1,0,1,0]
Input: [1,1,1,0,1,1,1,1], 2
Expected Output: [0,0,0,0,0,1,1,0]
#include <iostream>
using namespace std;
void cellCompete(int cells[], int days) {
int temp[8];
while (days--) {
for (int i = 0; i < 8; i++) {
int left = (i == 0) ? 0 : cells[i - 1];
int right = (i == 7) ? 0 : cells[i + 1];
temp[i] = (left == right) ? 0 : 1;
}
for (int i = 0; i < 8; i++) {
cells[i] = temp[i];
}
}
}
int main() {
int cells[] = {1, 0, 0, 0, 0, 1, 0, 0};
int days = 1;
cellCompete(cells, days);
cout << "Final state: ";
for (int i = 0; i < 8; i++) {
cout << cells[i] << " ";
}
return 0;
}
n = 8
.Mooshak, the mouse, needs to find a path to a huge chunk of cheese in a maze represented as a 2D grid.
0
represents walls (Mooshak cannot pass).1
represents valid paths.9
represents the cheese (goal).(0,0)
and can only move up, down, left, or right.Write a function isPath(int** grid, int m, int n)
that returns:
Input:
[[1, 1, 1],
[9, 1, 1],
[0, 1, 0]]
Output: 1
Explanation: Mooshak can move (0,0) → (1,0)
or (0,0) → (0,1) → (1,1) → (1,0)
.
Input:
luaCopyEdit[[0, 0, 0],
[9, 1, 1],
[0, 1, 1]]
Output: 0
Explanation: Mooshak cannot move as (0,0)
is blocked by walls.
#include <iostream>
using namespace std;
#define N 8
bool isPathHelper(int maze[N][N], int x, int y) {
if (x < 0 || y < 0 || x >= N || y >= N || maze[x][y] == 0) {
return false;
}
if (maze[x][y] == 9) {
return true;
}
maze[x][y] = 3; // Mark as visited
if (isPathHelper(maze, x - 1, y)) return true; // Move up
if (isPathHelper(maze, x, y + 1)) return true; // Move right
if (isPathHelper(maze, x + 1, y)) return true; // Move down
if (isPathHelper(maze, x, y - 1)) return true; // Move left
maze[x][y] = 1; // Unmark if path not found
return false;
}
bool isPath(int maze[N][N]) {
return isPathHelper(maze, 0, 0);
}
int main() {
int maze[N][N] = {
{1, 0, 1, 1, 1, 0, 0, 1},
{1, 0, 0, 0, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 1, 0, 9, 0, 1, 1},
{1, 1, 1, 0, 1, 0, 0, 1},
{1, 0, 1, 0, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 1, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1}
};
cout << "Is path available: " << isPath(maze) << endl;
return 0;
}
O(N^2)
, where N
is the size of the grid.Both Cell Competition Simulation and Maze Pathfinding Algorithm are powerful problem-solving techniques commonly used in technical interviews and competitive programming.