Shortest Walk Through an Office Floor Breaking at Most K Walls

Last updated: November 29, 2026

Quick Overview

Given a grid of open cells (0) and walls (1), find the minimum number of steps from the top-left to the bottom-right when you may pass through at most k walls. Return -1 if no such walk exists.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given a grid of open cells (0) and walls (1), find the minimum number of steps from the top-left to the bottom-right when you may pass through at most k walls. Return -1 if no such walk exists.

A Meta onsite BFS question with an extra dimension of state. Framed as a facilities robot that can open a limited number of locked doors. Interviewers look for (row, col, remaining) state, a pruning rule that keeps the state space small, and the Manhattan shortcut when k is large.

What the Interviewer Expects
  • Add remaining removals to the BFS state
  • Explain why BFS by levels gives the minimum steps
  • Prune states that arrive with fewer removals left than a previous visit
  • Use the shortcut that k >= R + C - 2 always allows the Manhattan path
  • Handle start equals target
Key Topics to Cover
BFS with state
Grid traversal
Pruning
Shortest path
Matrix
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Why is it safe to keep only the maximum remaining removals per cell?
  • How would A* with Manhattan distance help on huge grids?
  • What if each wall had a different removal cost?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Grid up to 40 x 40, 0 <= k <= R * C, start and target are open.
  • Moves in four directions, one step each.
  • Return the minimal step count with at most k walls crossed....
High-Level Design

State is (r, c, left). BFS by layers gives minimal steps. A visit with more removals left dominates one with fewer at the same step count or later, so store best_left[r][c] and only enqueue a stat...


Submit Your Answer
Markdown supported