← TCS bank

TCS · Question 5

Solve a Maze Problem Using Backtracking

C++code⏱ O(4^(n*m))💾 O(n²)
Service-based

Problem

Find all paths from start to destination in a maze.

Approach

DFS with visited marking counts every simple path to the exit.

Time O(4^(n*m))Space O(n²)

How it works

  1. 1DFS explores every open neighbour.
  2. 2Visited marks prevent reuse; unmark on backtrack.
  3. 3Reaching the exit counts one path.

Sample input / output

Input:
3x3 open maze, start = (0, 0), exit = (2, 2)
Output:
12

Constraints

Binary maze; 1 = open, 0 = wall.

Solution — read it, then walk it

Time O(4^(n*m))Space O(n²)Branches 2Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
STARTinclude <iostream>include <vector>using namespace stdDEFINEcountPaths(vector<vector<int>>&maze, int r, int c…DEFINE n = maze.size(), m =maze[0].size()if (r < 0 || r >= n ||c < 0 || c >= m ||maze[r][c] == 0 |…if (r == n - 1 && c ==m - 1) return 1vis[r][c] = 1DEFINE total =countPaths(maze, r + 1, c,vis) + countPaths(maze, r …+ countPaths(maze, r, c +1, vis) + countPaths(maze,r, c - 1, vis)vis[r][c] = 0RETURN totalDEFINE main()vector<vector<int>> maze ={{1, 1, 1}, {1, 1, 1}, {1,1, 1}}vector<vector<int>> vis(3,vector<int>(3, 0))cout << countPaths(maze, 0,0, vis) << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/18

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits