{"id":"6b093ddebd4755deb67ee071","slug":"grid-shortest-path","title":"Shortest path in a maze","summary":"A warehouse robot looks for the shortest route on a grid with obstacles. BFS in an unweighted graph – and why breadth-first rather than depth-first.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["graphs","bfs","shortest-path","matrix"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** Minimum number of moves from 'S' to 'E' ('#' = wall, 4 directions), or -1. */\nfunction shortestPath(grid: string[]): number {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":6,"tests":"function serpentine(rows, cols) {\n  // even rows are open; odd rows are walls with a gap alternating between the right and the left edge\n  const grid = [];\n  for (let r = 0; r < rows; r++) {\n    if (r % 2 === 0) grid.push('.'.repeat(cols));\n    else if (r % 4 === 1) grid.push('#'.repeat(cols - 1) + '.');\n    else grid.push('.' + '#'.repeat(cols - 1));\n  }\n  grid[0] = 'S' + grid[0].slice(1);\n  const last = rows - 1;\n  grid[last] = 'E' + grid[last].slice(1);\n  return grid;\n}\n\ntest('straight line and neighbours', () => {\n  expect(shortestPath(['S.E'])).toBe(2);\n  expect(shortestPath(['SE'])).toBe(1);\n  expect(shortestPath(['S', '.', 'E'])).toBe(2);\n});\n\ntest('around an obstacle', () => {\n  expect(shortestPath(['S#E', '.#.', '...'])).toBe(6);\n});\n\ntest('unreachable target', () => {\n  expect(shortestPath(['S#E'])).toBe(-1);\n  expect(shortestPath(['S.#', '##.', '..E'])).toBe(-1);\n});\n\ntest('the shortest of several routes', () => {\n  const grid = [\n    'S....',\n    '.###.',\n    '.#E#.',\n    '.#.#.',\n    '.....',\n  ];\n  expect(shortestPath(grid)).toBe(8);\n});\n\ntest('an open field', () => {\n  expect(shortestPath(['S....', '.....', '.....', '....E'])).toBe(7);\n});\n\ntest('performance: 399 × 400 serpentine, route of 80 198 moves', () => {\n  expect(shortestPath(serpentine(399, 400))).toBe(80198);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Minimum number of moves from 'S' to 'E' ('#' = wall, 4 directions), or -1.\n * @param {string[]} grid\n * @returns {number}\n */\nfunction shortestPath(grid) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":6,"tests":"function serpentine(rows, cols) {\n  // even rows are open; odd rows are walls with a gap alternating between the right and the left edge\n  const grid = [];\n  for (let r = 0; r < rows; r++) {\n    if (r % 2 === 0) grid.push('.'.repeat(cols));\n    else if (r % 4 === 1) grid.push('#'.repeat(cols - 1) + '.');\n    else grid.push('.' + '#'.repeat(cols - 1));\n  }\n  grid[0] = 'S' + grid[0].slice(1);\n  const last = rows - 1;\n  grid[last] = 'E' + grid[last].slice(1);\n  return grid;\n}\n\ntest('straight line and neighbours', () => {\n  expect(shortestPath(['S.E'])).toBe(2);\n  expect(shortestPath(['SE'])).toBe(1);\n  expect(shortestPath(['S', '.', 'E'])).toBe(2);\n});\n\ntest('around an obstacle', () => {\n  expect(shortestPath(['S#E', '.#.', '...'])).toBe(6);\n});\n\ntest('unreachable target', () => {\n  expect(shortestPath(['S#E'])).toBe(-1);\n  expect(shortestPath(['S.#', '##.', '..E'])).toBe(-1);\n});\n\ntest('the shortest of several routes', () => {\n  const grid = [\n    'S....',\n    '.###.',\n    '.#E#.',\n    '.#.#.',\n    '.....',\n  ];\n  expect(shortestPath(grid)).toBe(8);\n});\n\ntest('an open field', () => {\n  expect(shortestPath(['S....', '.....', '.....', '....E'])).toBe(7);\n});\n\ntest('performance: 399 × 400 serpentine, route of 80 198 moves', () => {\n  expect(shortestPath(serpentine(399, 400))).toBe(80198);\n});\n"},{"lang":"python","runner":"browser","starter":"def shortest_path(grid: list[str]) -> int:\n    \"\"\"Minimum number of moves from 'S' to 'E' ('#' = wall, 4 directions), or -1.\"\"\"\n    raise NotImplementedError\n","testCount":6,"tests":"def serpentine(rows, cols):\n    grid = []\n    for r in range(rows):\n        if r % 2 == 0:\n            grid.append(\".\" * cols)\n        elif r % 4 == 1:\n            grid.append(\"#\" * (cols - 1) + \".\")\n        else:\n            grid.append(\".\" + \"#\" * (cols - 1))\n    grid[0] = \"S\" + grid[0][1:]\n    grid[-1] = \"E\" + grid[-1][1:]\n    return grid\n\n\ndef check(grid, expected):\n    got = shortest_path(grid)\n    assert got == expected, f\"shortest_path({grid[:5]}): expected {expected}, got {got}\"\n\n\ndef test_straight_line_and_neighbours():\n    check([\"S.E\"], 2)\n    check([\"SE\"], 1)\n    check([\"S\", \".\", \"E\"], 2)\n\n\ndef test_around_an_obstacle():\n    check([\"S#E\", \".#.\", \"...\"], 6)\n\n\ndef test_unreachable_target():\n    check([\"S#E\"], -1)\n    check([\"S.#\", \"##.\", \"..E\"], -1)\n\n\ndef test_shortest_of_several_routes():\n    check([\"S....\", \".###.\", \".#E#.\", \".#.#.\", \".....\"], 8)\n\n\ndef test_open_field():\n    check([\"S....\", \".....\", \".....\", \"....E\"], 7)\n\n\ndef test_performance_serpentine():\n    check(serpentine(399, 400), 80198)\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\n\npublic static class Solution\n{\n    /// <summary>Minimum number of moves from 'S' to 'E' ('#' = wall, 4 directions), or -1.</summary>\n    public static int ShortestPath(string[] grid)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":6},{"lang":"java","runner":"judge0","starter":"class Solution {\n    /** Minimum number of moves from 'S' to 'E' ('#' = wall, 4 directions), or -1. */\n    static int shortestPath(String[] grid) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":6},{"lang":"go","runner":"judge0","starter":"package main\n\n// ShortestPath returns the minimum number of moves from 'S' to 'E' ('#' = wall, 4 directions), or -1.\nfunc ShortestPath(grid []string) int {\n\tpanic(\"not implemented\")\n}\n","testCount":6}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:54.201Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A warehouse robot moves on a grid: "},{"type":"text","text":".","marks":[{"type":"code"}]},{"type":"text","text":" is a free cell, "},{"type":"text","text":"#","marks":[{"type":"code"}]},{"type":"text","text":" is a shelf, "},{"type":"text","text":"S","marks":[{"type":"code"}]},{"type":"text","text":" is the start and "},{"type":"text","text":"E","marks":[{"type":"code"}]},{"type":"text","text":" is the charging station. In one move the robot steps to the neighbouring cell up, down, left or right. How many moves does it need to reach the station?"}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"The function gets the grid as a list of equally long strings (exactly one "},{"type":"text","text":"S","marks":[{"type":"code"}]},{"type":"text","text":" and one "},{"type":"text","text":"E","marks":[{"type":"code"}]},{"type":"text","text":") and returns the "},{"type":"text","text":"minimum","marks":[{"type":"bold"}]},{"type":"text","text":" number of moves from "},{"type":"text","text":"S","marks":[{"type":"code"}]},{"type":"text","text":" to "},{"type":"text","text":"E","marks":[{"type":"code"}]},{"type":"text","text":", or "},{"type":"text","text":"-1","marks":[{"type":"code"}]},{"type":"text","text":" when the station cannot be reached. "},{"type":"text","text":"S","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"E","marks":[{"type":"code"}]},{"type":"text","text":" cells are free."}]},{"type":"paragraph","content":[{"type":"text","text":"Signatures: "},{"type":"text","text":"shortestPath(grid)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"shortest_path(grid)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.ShortestPath","marks":[{"type":"code"}]},{"type":"text","text":" (C#, "},{"type":"text","text":"string[]","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"Solution.shortestPath","marks":[{"type":"code"}]},{"type":"text","text":" (Java, "},{"type":"text","text":"String[]","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"ShortestPath","marks":[{"type":"code"}]},{"type":"text","text":" (Go, "},{"type":"text","text":"[]string","marks":[{"type":"code"}]},{"type":"text","text":")."}]},{"type":"heading","attrs":{"level":2,"id":"examples"},"content":[{"type":"text","text":"Examples"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Grid"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Result"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"S.E\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"SE\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"S#E\", \".#.\", \"...\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"6","marks":[{"type":"code"}]},{"type":"text","text":" – around the shelf"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[\"S#E\"]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"-1","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"1 ≤ rows, columns ≤ 400","marks":[{"type":"code"}]},{"type":"text","text":" (up to 160,000 cells); a route can be tens of thousands of moves long."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"O(R · C)","marks":[{"type":"bold"}]},{"type":"text","text":" time, "},{"type":"text","text":"O(R · C)","marks":[{"type":"bold"}]},{"type":"text","text":" memory."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/shortest-path-in-binary-matrix/","title":"LeetCode 1091 – Shortest Path in Binary Matrix","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:54.203Z","updatedAt":"2026-11-27T08:22:54.203Z"}