(SPOJ) Matriz Escada - Solution

Link to the problem: http://br.spoj.com/problems/ESCADA14/


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

class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int rows = sc.nextInt();
        int cols = sc.nextInt();
       
        int[][] matrix = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }
       
        int rowStart = 0;
        boolean allMustBeZero = false;
        boolean stair = true;
        for (int i = 0; i < rows && stair; i++) {
            int firstNotZeroCol = 0;
            boolean foundNotZero = false;
            for (int j = 0; j < cols; j++) {
                if (!foundNotZero && matrix[i][j] != 0) {
                    firstNotZeroCol = j;
                    foundNotZero = true;
                    break;
                }
            }
           
            if (!foundNotZero) {
                rowStart = i+1;
                allMustBeZero = true;
                break;
            }
            else {
                for (int j = i+1; j < rows; j++) {
                    for (int k = 0; k <= firstNotZeroCol; k++) {
                        if (matrix[j][firstNotZeroCol] != 0) {
                            stair = false;
                            break;
                        }
                    }
                }
            }
        }
       
        if (allMustBeZero) {
            for (int i = rowStart; i < rows && stair; i++) {
                for (int j = 0; j < cols; j++) {
                    if (matrix[i][j] != 0) {
                        stair = false;
                        break;
                    }
                }
            }
        }
       
        if (stair) {
            System.out.println("S");
        }
        else {
            System.out.println("N");
        }
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução