题目链接
井字游戏
题目描述
注意点
- 1 <= board.length == board[i].length <= 100
- 输入一定遵循井字棋规则
解答思路
- 如果某一方想要获胜,则其需要占满某一行或某一列或对角线,所以只需要根据第一行和第一列判断是否填充完某一行或某一列或对角线即可
- 对于第一行,可以根据该行每一列的字符判断该列是否被该字符填充完(如果是空则可直接跳过)
- 对于第一列,可以根据该列每一行的字符判断该行是否被该字符填充完(如果是空则可直接跳过)
- 对于左上角,需要额外判断主对角线是否被该字符填充完(如果是空则可直接跳过)
- 对于右上角,需要额外判断副对角线是否被该字符填充完(如果是空则可直接跳过)
- 如果没有一方获胜,还需要判断游戏是已结束(平局)还是未结束,是否结束取决于棋盘中是否还有位置未填充字符,所以需要用isFinished记录棋盘中是否还有空字符,如果有说明未结束
代码
class Solution {
int n;
boolean isFinished;
public String tictactoe(String[] board) {
isFinished = true;
n = board.length;
// 判断字符是否填充完某一行
for (int row = 0; row < n; row++) {
if (board[row].charAt(0) == ' ') {
isFinished = false;
} else {
char c = board[row].charAt(0);
if (isRow(row, c, board)) {
return String.valueOf(c);
}
}
}
// 判断字符是否填充完某一列
for (int col = 0; col < n; col++) {
if (board[0].charAt(col) == ' ') {
isFinished = false;
} else {
char c = board[0].charAt(col);
if (isCol(col, c, board)) {
return String.valueOf(c);
}
}
}
// 左上角的点判断是否满足主对角线
if (board[0].charAt(0) == ' ') {
isFinished = false;
} else {
char c = board[0].charAt(0);
if (isMain(c, board)) {
return String.valueOf(c);
}
}
// 右上角的点判断是否满足副对角线
if (board[0].charAt(n - 1) == ' ') {
isFinished = false;
} else {
char c = board[0].charAt(n - 1);
if (isSub(c, board)) {
return String.valueOf(c);
}
}
return isFinished ? "Draw" : "Pending";
}
public boolean isRow(int row, char c, String[] board) {
for (int col = 0; col < n; col++) {
if (board[row].charAt(col) == c) {
continue;
}
if (board[row].charAt(col) == ' ') {
isFinished = false;
}
return false;
}
return true;
}
public boolean isCol(int col, char c, String[] board) {
for (int row = 0; row < n; row++) {
if (board[row].charAt(col) == c) {
continue;
}
if (board[row].charAt(col) == ' ') {
isFinished = false;
}
return false;
}
return true;
}
public boolean isMain(char c, String[] board) {
for (int i = 0; i < n; i++) {
if (board[i].charAt(i) == c) {
continue;
}
if (board[i].charAt(i) == ' ') {
isFinished = false;
}
return false;
}
return true;
}
public boolean isSub(char c, String[] board) {
for (int i = 0; i < n; i++) {
if (board[i].charAt(n - i - 1) == c) {
continue;
}
if (board[i].charAt(n - i - 1) == ' ') {
isFinished = false;
}
return false;
}
return true;
}
}
关键点
- 井字棋取胜的规律
- 注意边界问题