This page is still under construction.

Parts of this page are still being built. What you see may change.

Wall Climbing

Interview

Time limit1sMemory limit256 MB

Summary
On a grid with walls, each step costs 1 second but moving between two cells that both touch a wall is free; find the minimum time from S to E.
Level

Medium5 of 10

Topics
Graph, BFS, Shortest path, Implementation
Solved
No attempts yet

Problem

Luciu wants to travel from the start point to the end point of a map that is HH tall and WW wide.

  • The map is a grid with HH rows and WW columns. Each cell is either a wall or an empty cell.

  • Luciu can move one cell at a time to an adjacent cell in one of the four directions: up, down, left, right. He cannot move onto a wall.

  • Moving one cell takes Luciu 1 second.

  • However, when Luciu climbs along a wall, he can move to an adjacent cell in one of the four directions in an instant (in 0 seconds).

    • An empty cell is called a cell adjacent to a wall if one of the cells directly above, below, left, or right of it is a wall.
    • Moving from a cell adjacent to a wall to another cell adjacent to a wall is called climbing along a wall.

Find the minimum time it takes Luciu to travel from the start point to the end point of the map.

Input

The first line gives HH and WW, separated by a space. The map is a grid with HH rows and WW columns.

From the second line, HH lines follow, each giving WW characters that describe the map.

  • # denotes a wall.
  • . denotes an empty cell.
  • S denotes the start point of the map. The start point is an empty cell.
  • E denotes the end point of the map. The end point is an empty cell.

Output

Print the minimum time it takes Luciu to travel from the start point to the end point of the map.

Constraints

  • 1≤H≤5001 \le H \le 500
  • 1≤W≤5001 \le W \le 500
  • Every cell of the grid is given as one of the characters ., #, S, E.
  • Exactly one start point S and exactly one end point E are given.
  • All cells on the outermost border of the map (column 1, column WW, row 1, row HH) are walls.
  • The case where the end point is unreachable from the start point is not given.

Examples2

  1. Example 1

    Input
    5 5
    #####
    #..E#
    #.S.#
    #...#
    #####
    
    Expected output
    1
    
  2. Example 2

    Input
    10 10
    ##########
    #........#
    #...#....#
    #........#
    #.E....S.#
    #........#
    #........#
    ##.......#
    #........#
    ##########
    
    Expected output
    2