Monday, 7 December 2015

Grid challenge

Problem Statement
Given a squared sized grid G of size N in which each cell has a lowercase letter. Denote the character in the ith row and in the jth column as G[i][j].
You can perform one operation as many times as you like: Swap two column adjacent characters in the same row G[i][j] and G[i][j+1] for all valid i,j.
Is it possible to rearrange the grid such that the following condition is true?
G[i][1]G[i][2]G[i][N] for 1iN and 
G[1][j]G[2][j]G[N][j] for 1jN
In other words, is it possible to rearrange the grid such that every row and every column is lexicographically sorted?
Notec1c2, if letter c1 is equal to c2 or is before c2 in the alphabet.
Input Format
The first line begins with T, the number of testcases. In each testcase you will be given N. The following N lines contain N lowercase english alphabet each, describing the grid.
Output Format
Print T lines. On the ith line print YES if it is possible to rearrange the grid in the ith testcase or NO otherwise.
Constraints 
1T100 
1N100 
Gij will be a lower case letter
Sample Input
1
5
ebacd
fghij
olmkn
trpqs
xywuv
Sample Output
YES
Explanation
The grid in the first and only testcase can be reordered to
abcde
fghij
klmno
pqrst
uvwxy
This fulfills the condition since the rows 1, 2, ..., 5 and the columns 1, 2, ..., 5 are all lexicographically sorted.




import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args)throws IOException{
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        int t = Integer.parseInt(s);    
        
        for(int i = 0 ; i < t ; i++ )
            {
            int j; 
            s = br.readLine();
            int n = Integer.parseInt(s); 
            char x[][] = new char[n][n];
            String in[] = new String[n];
            String out[] = new String[n];
            for( j = 0 ; j < n ; j++ )
                {
                in[j] = br.readLine();
                x[j] = in[j].toCharArray();
                Arrays.sort(x[j]);
                out[j] = new String(x[j]);
            }      
         /*  for( j = 0 ; j < n ; j++ )
                System.out.println(out[j]);*/
            int flag = 0;
            for( j = 0 ; j < n-1 ; j++ )
                {
                for( int k = 0 ; k < n ; k++ )
                    {
                    if(out[j].charAt(k) > out[j+1].charAt(k))
                        {
                        flag = 1;
                        break;
                    }
                }
            }
            if(flag == 0)
                System.out.println("YES");
            else
                System.out.println("NO");
        }
    }
}

No comments:

Post a Comment