题解 | #井字棋#

井字棋

http://www.nowcoder.com/practice/0375c1d206ef48a3894f72aa07b2fdde

import java.util.Scanner;

public class Main {
    public static boolean win(char[][] arr, char c) {
        boolean flag = false;
        // 验证行
        for (int i = 0; i < arr.length; i++) {
            flag = true; // 是否满足
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] != c) {
                    flag = false;
                }
            }
            if (flag) {
                return flag;
            }
        }

        // 验证列
        for (int i = 0; i < arr.length; i++) {
            flag = true; // 是否满足
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[j][i] != c) {
                    flag = false;
                }
            }
            if (flag) {
                return flag;
            }
        }

        // 验证从左上角到左下角
        for (int i = 0; i < arr.length; i++) {
            flag = true; // 是否满足
            if (arr[i][i] != c) {
                flag = false;
                break;
            }
        }
        if (flag) {
            return flag;
        }

        // 验证从左下角到右上角
        for (int i = arr.length - 1; i >= 0 ; i--) {
            flag = true; // 是否满足
            if (arr[i][2 - i] != c) {
                flag = false;
                break;
            }
        }
        if (flag) {
            return flag;
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = 3;
        char[][] arr = new char[n][n];

        for (int i = 0; i < n; i++) {
            String s = sc.nextLine();
            String[] tmp = s.split(" ");
            for (int j = 0; j < n; j++) {
                arr[i][j] = tmp[j].charAt(0);
            }
        }
        boolean k = win(arr, 'K');
        boolean b = win(arr, 'B');
        if (k) {
            System.out.println("KiKi wins!");
        } else if (b) {
            System.out.println("BoBo wins!");
        } else {
            System.out.println("No winner!");
        }
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务