This page is still under construction.

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

Royal Decree

Interview

Time limit2sMemory limit512 MB

Summary
Given a friendship graph and bound d, find the largest possible difference between richest and poorest that satisfies the friend-difference constraint, or -1 if unbounded.
Level

Medium6 of 10

Topics
Graph, Shortest path, BFS
Solved
No attempts yet

Problem

A kingdom has N people. The amount of money each person holds is a non-negative integer, and the people are numbered 1 through N.

One day the king proclaimed a decree. The money any person holds may differ from the money each of that person's friends holds by at most dd. In other words, for a person to hold xx, none of that person's friends may hold less than x−dx-d and none may hold more than x+dx+d.

Among all distributions that obey the decree, the people want the one where the gap between the richest person and the poorest person is as large as possible.

Given the number of people and the friendships, write a program that computes the largest possible gap.

Input

The first line contains the number of people NN (2≤N≤502 \le N \le 50).

The second line contains dd (0≤d≤10000 \le d \le 1000).

Each of the next NN lines describes the friendships. If the jj-th character of the ii-th line is Y, person ii and person jj are friends; if it is N, they are not. The ii-th character of the ii-th line is always N, and the jj-th character of the ii-th line equals the ii-th character of the jj-th line.

Output

Print on the first line the largest gap between the richest person and the poorest person over all distributions that obey the decree. If this gap is unbounded, print -1.

Explanation

Suppose there are only three people, person 1 is a friend of person 2, person 2 is a friend of person 3, and dd is 10. Giving person 1 100, person 2 110, and person 3 120 obeys the decree, so the gap reaches 20. If nobody is anybody's friend, no constraint applies at all and the gap is unbounded.

Examples3

  1. Example 1

    Input
    3
    10
    NYN
    YNY
    NYN
    
    Expected output
    20
    
  2. Example 2

    Input
    2
    1
    NN
    NN
    
    Expected output
    -1
    
  3. Example 3

    Input
    6
    1000
    NNYNNN
    NNYNNN
    YYNYNN
    NNYNYY
    NNNYNN
    NNNYNN
    
    Expected output
    3000