【发布时间】:2026-01-31 15:15:01
【问题描述】:
给定数组:
字符串[,] arr = 新字符串[n,n]。 如何检查每行、每列和两条对角线的元素是否相等?
这是一种井字游戏:编写一个控制台应用程序,接收 X 和 0 作为坐标的 N 个移动日期作为输入。 (0, 0) 是左上角, (2, 2) 是右下角。第一行是步数 N,从第二行开始,每行一个步数。第一手是玩家的 X,其次是玩家的手 0,然后是 X,依此类推。应用程序将分析收到的手,并显示获胜者:X,0 或如果没有获胜者则平局. 这是我尝试过的,但没有结果:
static void Main()
{
int numberOfMoves = Convert.ToInt32(Console.ReadLine());
const int size = 3;
string[,] boardGame = new string[size, size];
for (int i = 0; i < numberOfMoves; i++)
{
string strCoordinates = Console.ReadLine();
string[] lineCoordinates = strCoordinates.Split(' ');
int coordinateX = Convert.ToInt32(lineCoordinates[0]);
int coordinateY = Convert.ToInt32(lineCoordinates[1]);
const int value = 2;
boardGame[coordinateX, coordinateY] = i % value == 0 ? "X" : "0";
}
// CheckElements(boardGame); in construction
Console.Read();
}
static void CheckRows(int x, int y)
{
string[,] boardGame = new string[3, 3];
int cols = boardGame.GetLength(1);
const int value = 2;
for (int i = 0; i < cols; i++)
{
if ((boardGame[0, 0] == boardGame[0, 1] && boardGame[0, 1] == boardGame[0, value]) || (boardGame[1, 0] == boardGame[1, 1] && boardGame[1, 1] == boardGame[1, value]))
{
Console.WriteLine(boardGame[0, 0]);
}
if ((boardGame[1, 0] == boardGame[1, 1] && boardGame[1, 1] == boardGame[1, value]) || (boardGame[value, 0] == boardGame[value, 1] && boardGame[value, 1] == boardGame[value, value]))
{
Console.Write(boardGame[0, 0]);
}
}
Console.WriteLine(boardGame[x, y]);
}
static void CheckColumns(int x, int y)
{
string[,] boardGame = new string[3, 3];
int rows = boardGame.GetLength(0);
const int value = 2;
for (int i = 0; i < rows; i++)
{
if ((boardGame[0, 0] == boardGame[1, 0] && boardGame[1, 0] == boardGame[value, 0]) || (boardGame[0, 1] == boardGame[1, 1] && boardGame[1, 1] == boardGame[value, 1]))
{
Console.WriteLine(boardGame[0, 0]);
}
if ((boardGame[0, 1] == boardGame[1, 1] && boardGame[1, 1] == boardGame[value, 1]) || (boardGame[0, value] == boardGame[1, value] && boardGame[1, value] == boardGame[value, value]))
{
Console.WriteLine(boardGame[0, 1]);
}
}
Console.WriteLine(boardGame[x, y]);
}
static void CheckDiagonals(int x, int y)
{
string[,] boardGame = new string[3, 3];
int m = boardGame.Length;
const int value = 2;
for (int i = 0; i < m; i++)
{
m--;
for (int j = 0; j < m; j++)
{
if (boardGame[0, 0] == boardGame[1, 1] && boardGame[1, 1] == boardGame[value, value])
{
Console.WriteLine(boardGame[0, 0]);
}
}
}
Console.WriteLine(boardGame[x, y]);
}
【问题讨论】:
-
您的示例中没有包含
CheckElements(string[,] boardGame)函数。 -
@Creyke,这是真的,我没有写函数 CheckElements 因为我被卡住了。我首先在寻找更好的解决方案来检查行、列和对角线中的相等元素。我更新了我的代码,包括您提到的行的评论。
-
而不是 X 和 Y 使用 1 和 -1 然后伪代码
int[max] rows, int cols[max] , int diag[2] for(int x <max) { for(int y < max) { cols[x] += board[x,y]; rows[y] += board[x,y]; } diag[0] += board[x,x]; diag[1] += board[max-1-x, x]; }现在检查任何 cols 行或 diag 是否为 max 或 -max 然后有人获胜
标签: c# arrays string for-loop methods