题解 | #井字棋#

井字棋

https://www.nowcoder.com/practice/e1bb714eb9924188a0d5a6df2216a3d1

import java.util.*;

public class serve {
    public static boolean checkWon(int[][] board) {
        int[] chessman = new int[9];
        int s = 0;
        for (int j = 0; j <= 2; j++) {
            for (int i = 0; i <= 2; i++) {
                chessman[s] = board[j][i];
                s++;
            }
        }
        if (chessman[0] == chessman[1] && chessman[1] == chessman[2] &&
                chessman[0] == 1) {
            return true;
        } else if (chessman[3] == chessman[4] && chessman[4] == chessman[5] &&
                chessman[3] == 1) {
            return true;
        } else if (chessman[6] == chessman[7] && chessman[7] == chessman[8] &&
                chessman[6] == 1) {
            return true;
        } else if (chessman[0] == chessman[3] && chessman[3] == chessman[5] &&
                chessman[0] == 1) {
            return true;
        } else if (chessman[1] == chessman[4] && chessman[4] == chessman[7] &&
                chessman[1] == 1) {
            return true;
        } else if (chessman[2] == chessman[5] && chessman[8] == chessman[5] &&
                chessman[2] == 1) {
            return true;
        } else if (chessman[0] == chessman[4] && chessman[4] == chessman[8] &&
                chessman[0] == 1) {
            return true;
        } else if (chessman[2] == chessman[4] && chessman[4] == chessman[6] &&
                chessman[2] == 1) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        int[][] board = {{-1,1,0},{1,-1,1},{0,1,-1}};

        boolean result = checkWon(board);

        System.out.println(result);
    }
}

这个是我自己的想法,我选择先将二维数组中的代码保存至一个一维数组中只需判断,一维数组中相邻三个元素以及对角线上的元素是否都为一,如果都为一返回true,反之返回false;

import java.util.*;

public class Board {
    public static boolean checkWon(int[][] board) {
        // 检查行
        for (int i = 0; i < 3; i++) {
            if (board[i][0] == 1 && board[i][1] == 1 && board[i][2] == 1) {
                return true;
            }
        }
        // 检查列
        for (int j = 0; j < 3; j++) {
            if (board[0][j] == 1 && board[1][j] == 1 && board[2][j] == 1) {
                return true;
            }
        }
        // 检查对角线
        if ((board[0][0] == 1 && board[1][1] == 1 && board[2][2] == 1) ||
                (board[0][2] == 1 && board[1][1] == 1 && board[2][0] == 1)) {
            return true;
        }
        return false;
    }
}

这个是直接对二维数组直接进行检察,显然这个方法更简单,内存使用更少,速度更快

#每日一题挑战#
每日一题解题思路 文章被收录于专栏

每天坚持刷题,从简单题开始,分享自己的解题思路。 期待您的关注。

全部评论

相关推荐

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