java - 为什么即使附加了这么多条件,它仍然打印 "NO"?

标签 java arrays for-loop

我在 Hyperskill 上发现了这个问题,并且一直在努力解决它。解决方案也在那里,但对我来说毫无意义。

在某些设计风格中,如果 4x4 矩阵图案不包含相同颜色的 2x2 矩阵,则认为它看起来很漂亮。您的任务是编写程序,如果 4x4 矩阵看起来很漂亮,则输出“YES”,否则输出“NO”。

输入包含4行,每行包含4个符号,不同的符号代表不同的颜色:W代表白色,B-黑色,R-红色,G-绿色,Y-黄色。

示例输入 1: 万维网 BBBB 万维网 YYYY

示例输出 1: 是的

示例输入 2: BBBB 世界银行 世界银行 BBBB

示例输出 2: 否

    String[] arr = new String[4];
    for (int i = 0; i < 4; i++) {
        arr[i] = scanner.next();
    }

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (arr[i].charAt(j) == arr[i + 1].charAt(j) && arr[i].charAt(j) == arr[i].charAt(j + 1)
                    && arr[i].charAt(j) == arr[i + 1].charAt(j + 1)) {
                System.out.println("NO");
                return;
            }
        }
    }

    System.out.println("YES");

最佳答案

我将给出我的解决方案并解释其工作原理,希望这会有所帮助。

String x="";
while(scanner.hasNextLine()){
    x+=scanner.nextLine();
}
//The above just combines the entire thing into one string length 16 to make it faster to code

boolean yes= true;
//preseted to true, if a uniformly colored 2by2 is found this becomes false

int[] topLefts = {0,1,2,4,5,6,8,9,10,12,13,14} 
//top Left corner of each possible 2 by 2 matrix

for(int i: top Lefts){//iterating over an array
    if(x.charAt(i)==x.charAt(i+1)&&x.charAt(i+4)==x.charAt(i+1)
         &&x.charAt(i+4)==x.charAt(i+5)) yes = false;
}
//This checks if the chars representing each box in the 2by2 are the same
//If even one 2by2 is colored the same, yes becomes true.

if(yes) System.out.println("YES");
else System.out.println("NO");

关于java - 为什么即使附加了这么多条件,它仍然打印 "NO"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59087170/

相关文章:

javascript - 如何复制数组(字符串)中的前一个值

Java,如何在java中的方法之间发送数组?

c++ - 仅在 vector 末尾打印新行 - "if"循环之外的 "for"语句

c++ - 我正在尝试遍历对象 vector 并打印对象的每个元素

jquery - 选择单个类元素

java - 从 JPA/EJB3 持久性上下文中分离实体

java - 从文本文件中列出客户的列表

java - 我可以使用 JAXB 编码自己的数据结构吗?

java - 将整数传递给java中的运行线程

arrays - Ruby - 转换多个数组以生成哈希