leetcode 面试题 16.04. 井字游戏,简单快速的解题思路
2020-07-14 06:14
507 查看
面试题 16.04. 井字游戏
题目:
设计一个算法,判断玩家是否赢了井字游戏。输入是一个 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"; } }
欢迎大家一起交流。
相关文章推荐
- leetcode作业记录总结,先从简单题开始吧(小白参考各路大神解题思路)
- leetCode 11.Container With Most Water (数轴上容器) 解题思路和方法
- Leetcode第12题解题思路
- leetCode 27.Remove Element (删除元素) 解题思路和方法
- [LeetCode] 179. Largest Number 解题思路
- 快速构建基于代码级性能测试方法的一种思路和简单实现
- LeetCode Weekly Contest 29解题思路
- mysql面试题及其解题思路(一)
- leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法
- leetCode 44.Wildcard Matching (通配符匹配) 解题思路和方法
- leetcode107c语言解题思路
- leetCode 48.Rotate Image (旋转图像) 解题思路和方法
- LeetCode Weekly Contest 46解题思路
- [LeetCode] Maximum Subarray 解题思路
- [LeetCode] Maximum Product Subarray 解题思路
- LeetCode Weekly Contest 44解题思路
- 【LeetCode-动态规划】Climbing Stairs【较重要:含dp解题思路套路】
- 面试题56 - I. 数组中数字出现的次数(Leetcode)最简单解释
- leetCode 75.Sort Colors (颜色排序) 解题思路和方法
- leetCode 116.Populating Next Right Pointers in Each Node (为节点填充右指针) 解题思路和方法