Cerinta completa

Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not.

Example

The grid is illustrated below.

a b c
a d e
e f g

The rows are already in alphabetical order. The columns a a e, b d f and c e g are also in alphabetical order, so the answer would be YES. Only elements within the same row can be rearranged. They cannot be moved to a different row.

Function Description

Complete the gridChallenge function in the editor below.

gridChallenge has the following parameter(s):

  • string grid[n]: an array of strings

Returns

  • string: either YES or NO

Input Format

The first line contains , the number of testcases.

Each of the next sets of lines are described as follows:
– The first line contains , the number of rows and columns in the grid.
– The next lines contains a string of length

Constraints



Each string consists of lowercase letters in the range ascii[a-z]

Output Format

For each test case, on a separate line print YES if it is possible to rearrange the grid alphabetically ascending in both its rows and columns, or NO otherwise.

Sample Input

STDIN   Function
-----   --------
1       t = 1
5       n = 5
ebacd   grid = ['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv']
fghij
olmkn
trpqs
xywuv

Sample Output

YES

Explanation

The x grid in the test case 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 alphabetically sorted.


Limbajul de programare folosit: cpp14

Cod:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

// Algorithm: Sort each row lexicographically, then check if each of the columns are lexicographically sorted
// Runtime: O(n^2) -> O(nlogn) to sort every row, but it takes O(n^2) time to check that every column is sorted
int main() {
	int T;
	cin>>T;
	while(T > 0) {
		int N;
		cin>>N;
		string *matrix = new string[N];
		// Read input, sort every row
		for(int i = 0; i < N; i++) {
			cin>>matrix[i];
			sort(matrix[i].begin(), matrix[i].end());
		}
		bool arrangeable = true;
		for(int i = 0; i < N; i++) {
			for(int j = 1; j < N; j++) {
				if(matrix[j][i] < matrix[j-1][i]) {
					arrangeable = false;
				}
			}
			// Small optimization: Break immediately if we've found that a column isn't sorted
			if(!arrangeable) {
				break;
			}
		}
		if(arrangeable) {
			cout<<"YES\n";
		} else {
			cout<<"NO\n";
		}
		T--;
	}
    return 0;
}

Scor obtinut: 1.0

Submission ID: 464603049

Link challenge: https://www.hackerrank.com/challenges/grid-challenge/problem

Grid Challenge