题目: 设计一个算法,判断玩家是否赢了井字游戏。输入是一个 N x N 的数组棋盘,由字符" ",“X"和"O"组成,其中字符” "代表一个空位。
以下是井字游戏的规则:
1、玩家轮流将字符放入空位(" “)中。 2、第一个玩家总是放字符"O”,且第二个玩家总是放字符"X"。 3、 "X"和"O"只允许放置在空位中,不允许对已放有字符的位置进行填充。 4、当有N个相同(且非空)的字符填充任何行、列或对角线时,游戏结束,对应该字符的玩家获胜。 当所有位置非空时,也算为游戏结束。 5、如果游戏结束,玩家不允许再放置字符。 如果游戏存在获胜者,就返回该游戏的获胜者使用的字符(“X"或"O”); 6、如果游戏以平局结束,则返回 “Draw”;如果仍会有行动(游戏未结束),则返回 “Pending”。
示例 1:
输入: board = [“O X”," XO",“X O”] 输出: “X”
示例 2:
输入: board = [“OOX”,“XXO”,“OXO”] 输出: “Draw” 解释: 没有玩家获胜且不存在空位
示例 3:
输入: board = [“OOX”,“XXO”,"OX "] 输出: “Pending” 解释: 没有玩家获胜且仍存在空位
提示: 1 <= board.length == board[i].length <= 100 输入一定遵循井字棋规则
题目来源:力扣(LeetCode) https://leetcode-cn.com/problems/tic-tac-toe-lcci
一般的思路是单独的先遍历行,再遍历列,最后遍历左右对角线。这样重复循环的次数多,这里提供一个简化,循环次数少的方法。
解题步骤:
遍历字符串数组,将其映射到二维整数数组中,其中 “O” 对应 1、“X” 对应 -1、" " 对应 0;外循环遍历左右对角线,累加元素数值;内循环以左对角线元素为遍历基准,遍历到左对角上的元素,同时分别累加对应行与列的数,若和为 board.length,则返回 “O”,若和为 -board.length,则返回 “X”,若没有胜利者,判断空字符标记位是否为空值,是,返回 “Pending”,否则返回 “Draw”。代码:
public static String tictactoe(String[] board) { int count1 = 0; int count2 = 0; int count0 = 0; int count01 = 0; int[][] twoArray = new int[board.length][board.length]; char nullChar = '#'; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board.length; j++) { if(board[i].charAt(j) == 'X'){ twoArray[i][j] = -1; }else if(board[i].charAt(j) == 'O'){ twoArray[i][j] = 1; }else{ twoArray[i][j] = 0; nullChar = ' '; } } } // 外循环 for (int i = 0; i < board.length; i++) { count0 += twoArray[i][i]; count01 += twoArray[i][board.length-1-i]; // 内循环 for (int j = 0; j < board.length; j++) { count1 = count1+twoArray[i][j]; count2 = count2+twoArray[j][i]; if(count1 == board.length || count2 == board.length || count0 == board.length || count01 == board.length){ return "O"; } if(count1 == -board.length || count2 == -board.length || count0 == -board.length || count01 == -board.length){ return "X"; } } count1 = 0; count2 = 0; } // 没有胜利者,判断是继续还是平局 if (nullChar == ' '){ return "Pending"; }else{ return "Draw"; } }欢迎大家一起交流。