{"id":"6b093ddebd4755deb67ee071","slug":"grid-shortest-path","title":"Najkrótsza droga w labiryncie","summary":"Robot magazynowy szuka najkrótszej trasy po siatce z przeszkodami. BFS w grafie nieważonym – dlaczego właśnie wszerz, a nie w głąb.","servedLang":"pl","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":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Robot w magazynie porusza się po siatce: "},{"type":"text","text":".","marks":[{"type":"code"}]},{"type":"text","text":" to wolne pole, "},{"type":"text","text":"#","marks":[{"type":"code"}]},{"type":"text","text":" – regał, "},{"type":"text","text":"S","marks":[{"type":"code"}]},{"type":"text","text":" – start, "},{"type":"text","text":"E","marks":[{"type":"code"}]},{"type":"text","text":" – stacja ładowania. W jednym ruchu robot przechodzi na sąsiednie pole w górę, w dół, w lewo albo w prawo. Ile ruchów potrzeba, żeby dojechać do stacji?"}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"Funkcja dostaje siatkę jako listę napisów jednakowej długości (dokładnie jedno "},{"type":"text","text":"S","marks":[{"type":"code"}]},{"type":"text","text":" i jedno "},{"type":"text","text":"E","marks":[{"type":"code"}]},{"type":"text","text":") i zwraca "},{"type":"text","text":"minimalną","marks":[{"type":"bold"}]},{"type":"text","text":" liczbę ruchów z "},{"type":"text","text":"S","marks":[{"type":"code"}]},{"type":"text","text":" do "},{"type":"text","text":"E","marks":[{"type":"code"}]},{"type":"text","text":" albo "},{"type":"text","text":"-1","marks":[{"type":"code"}]},{"type":"text","text":", gdy dojazd jest niemożliwy. Pola "},{"type":"text","text":"S","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"E","marks":[{"type":"code"}]},{"type":"text","text":" są wolne."}]},{"type":"paragraph","content":[{"type":"text","text":"Sygnatury: "},{"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":"przyklady"},"content":[{"type":"text","text":"Przykłady"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Siatka"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wynik"}]}]}]},{"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":" – dookoła regału"}]}]}]},{"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":"ograniczenia"},"content":[{"type":"text","text":"Ograniczenia"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"1 ≤ wiersze, kolumny ≤ 400","marks":[{"type":"code"}]},{"type":"text","text":" (do 160 000 pól); trasa może mieć dziesiątki tysięcy ruchów."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"oczekiwana-zlozonosc"},"content":[{"type":"text","text":"Oczekiwana złożoność"}]},{"type":"paragraph","content":[{"type":"text","text":"Czas "},{"type":"text","text":"O(R · C)","marks":[{"type":"bold"}]},{"type":"text","text":", pamięć "},{"type":"text","text":"O(R · C)","marks":[{"type":"bold"}]},{"type":"text","text":"."}]}]},"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"}