Quick out of the Harbour#3124

Quick out of the Harbour

1 second
32 megabytes
Very easy

Captain Clearbeard decided to go to the harbour for a few days so his crew could inspect and repair the ship. Now, a few days later, the pirates are getting landsick (Pirates get landsick when they don't get enough of the ship's rocking motion. That's why the pirates sometimes try to simulate that motion by standing on barrels and swaying side to side.). Before all of the pirates become too sick to row the boat out of the harbour, Captain Clearbeard decided to leave the harbour as quickly as possible.

Unfortunately, the harbour is not just a straight path to open sea. To protect the city from evil pirates, the entrance of the harbour is designed as a kind of maze with drawbridges in it. Every bridge takes some time to open, so it might be faster to take a detour. Your task is to help Captain Clearbeard find the fastest way to open sea.

The pirates can row as fast as one minute per grid cell on the map. The ship can move only horizontally or vertically on the map. Making a degree turn does not take any extra time.

Input

The first line of the input contains a single number: the number of test cases to follow. Each test case has the following format:

  • One line with three integers, , (3 \leq h; w \leq 500), and (0 \leq d \leq 50), the height and width of the map and the delay for opening a bridge.

  • lines with characters: the description of the map. The map uses the following characters:

    • S, the starting position of the ship.

    • ., water.

    • #, land.

    • @, a drawbridge.

Each harbour is completely surrounded with land, except for the single entrance.

Output

For every test case in the input, the output should contain one integer on a single line: the travel time of the fastest route to open sea. There is always a route to open sea. Note that the open sea does not appear on the map, so you need to move outside of the map to reach open sea.

Examples

Example 1

Loading
Loading