Under construction

Still being built. Things may change

Edit distance on table

Time limit3sMemory limit1024 MB

Summary
Given a grid of letters and a string T, find the smallest edit distance between T and any string spelled by a walk on the grid.
Level

Medium7 of 10

Topics
Dynamic programming, Graph, String matching
Solved
No attempts yet

Problem

A table has HH rows and WW columns. Each cell contains one lowercase English letter.

Build a string with the following steps.

  1. Pick a cell and let SS be a string of length 1 containing the letter in that cell.
  2. Choose one of the following.
    • Stop building SS.
    • Choose one of the four cells that share an edge with the current cell. Append its letter to SS, move to that cell, and repeat step 2.

You are given a string TT. Your goal is to minimize the edit distance between SS and TT.

The edit distance between strings UU and VV is the minimum number of operations needed to turn UU into VV. The allowed operations are:

  • Replace one character with another.
  • Insert one character.
  • Delete one character.

Input

The first line contains HH and WW. Each of the next HH lines describes one row of the table. The last line contains the string TT. TT is not empty and its length is at most 20002000. The letters in the table and TT are all lowercase English letters.

Output

Print the minimum possible edit distance between SS and TT on one line.

Examples1

  1. Example 1

    Input
    2 2
    ab
    ar
    abracadabra
    
    Expected output
    2