Under construction

Still being built. Things may change

Erratic Ants

Interview

Time limit2sMemory limit256 MB

Summary
Given a recorded walk on a grid, find the fewest steps from start to end using only walked edges or their reverses.
Level

Medium5 of 10

Topics
BFS, Graph, Shortest path
Solved
No attempts yet

Problem

An ant colony is out looking for food. The ground around the colony is full of traps and obstacles, and predators are hiding there too, so foraging is hard. Luckily the colony has one ant who fits the job. Max is neither clever nor diligent, but his luck holds. On every trip he has ever made he stayed on safe ground, and sooner or later he always reached a food source and reported it back.

The trouble is that Max almost never walks anything close to a shortest route. He does report the path he took, one step at a time and exactly, however long and winding it is. Find the shortest route contained in the directions Max reported, so the colony can carry food with less walking.

Input

The first line contains the number of paths Max reported, nn (1≤n≤1001 \le n \le 100). A blank line follows, then the descriptions of the nn paths. A blank line separates each pair of path descriptions.

Each path description starts with the number of steps in that path, ss (0≤s≤600 \le s \le 60). The next ss lines each contain one of the upper-case letters N, E, S, W, meaning a step to the north, east, south, or west. Each step moves Max one unit of distance. Every path starts at the colony and ends at a food source.

When you look for a shortest route, you may only take steps that Max already took, or those same steps in reverse.

Output

For each path, print the number of steps in a shortest route from the colony to that path's food source, one integer per line, in the order the paths are given.

Examples1

  1. Example 1

    Input
    3
    
    8
    S
    E
    E
    E
    N
    W
    S
    S
    
    4
    S
    E
    N
    W
    
    3
    S
    E
    N
    
    Expected output
    4
    0
    3