【问题标题】:Check for adjacent cells in a 5x6 matrix检查 5x6 矩阵中的相邻单元格
【发布时间】:2014-04-13 20:42:34
【问题描述】:

我有一个 5x6 矩阵,它是使用 Java Swing 中的单个按钮创建的。

我将它们命名为类似于棋盘,从左上角到右下角为 A1 到 F5。

现在,我想让用户只点击给定数量的相邻按钮,水平或垂直。

假设值为 4。因此,用户必须能够在矩阵中的任意位置仅选择 4 个垂直或水平相邻的按钮。

例如。 D2、C2、B2、A2(如果垂直选择)。 或者,如果水平选择,则可能是 D1、D2、D3、D4。

为矩阵中的任何一组按钮实现此功能的算法方式是什么?

【问题讨论】:

    标签: java algorithm logic


    【解决方案1】:

    这是代码,我添加了一些 cmets 以使其更清晰。

    请注意代码中的数组要排序

    逻辑

    横向

    A1 => 01
    A2 => 02
    A3 => 03
    A4 => 04
    
    So A2 - A1 = 1
    

    垂直

    A1 => 01
    B1 => 11
    C1 => 21
    D1 => 31
    
    So B1 - A1 = 10
    

    代码:

        public static void main(String[] args) {
            String[] spots0 = { "A1", "B1", "C1", "D1" };
            String[] spots1 = { "A1", "A2", "A3", "A4" };
            String[] spots2 = { "A1", "B1", "B2", "B3" };
    
            System.out.println(isCorrect(spots0) ? "correct" : "incorrect");
            System.out.println(isCorrect(spots1) ? "correct" : "incorrect");
            System.out.println(isCorrect(spots2) ? "correct" : "incorrect");
        }
    
        public static boolean isCorrect(String[] spots) {
            int NONE = -1;
            int HORIZONTAL = 1;
            int VERTICAL = 2;
    
            int pattern = NONE; //BY DEFAULT NONE
    
            for (int i = 0; i < spots.length - 1; i++) {
    
                //difference between 2 consecutive element in spots[]. If A2 - A1 = 1, and B1 - A1 = 10
                int diff = toNum(spots[i + 1]) - toNum(spots[i]);
    
                if (diff == 1) { // if HORIZONTAL
                    if (pattern == NONE) // if the first time
                        pattern = HORIZONTAL; // set pattern to vertical, this is used for later to check if any illigal change happen
                    else if (pattern == VERTICAL) { //if it was Vertical and changed, then error
                        return false;
                    }
                } else if (diff == 10) { // if VERTICAL
                    if (pattern == NONE) // if the first time
                        pattern = VERTICAL; // set pattern to horizontal, this is used for later to check if any illigal change happen
                    else if (pattern == HORIZONTAL) { //if it was Horizontal and changed, then error
                        return false;
                    }
    
                } else {
                    return false;
                }
            }
            return true;
        }
    
        public static int toNum(String s) {
            // A1 => 01 , B1 => 11, C2 => 22
            return Integer.parseInt("" + ((int)s.charAt(0) - 'A') + s.charAt(1));
        }
    

    【讨论】:

    • 哇!这太棒了!
    • @KanishkaGanguly 我刚刚注意到这个问题仍然有待解答。如果上述答案正确,请标记为已解决。谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    相关资源
    最近更新 更多