I am assuming that in your grid, 1 means X, 2 means O and 0 means nobody.
I think of tic tac toe in terms of lines, so let's put that idea into the program. Here is a line that let's you get the player at any position:
interface Line {
int get(int n);
}
Now we can write methods that return Line implementations for rows, columns and diagonals.
Line row(int[][] grid, int rowNumber) {
return columnNumber -> grid[rowNumber][columnNumber];
}
Line column(int[][] grid, int columnNumber) {
return rowNumber -> grid[rowNumber][columnNumber];
}
Line rightDiagonal(int[][] grid) {
return i -> grid[i][i];
}
Line leftDiagonal(int[][] grid, int length) {
return i -> grid[i][length - 1 - i];
}
and a method to get all the lines in the grid:
private List<Line> makeLines(int[][] grid) {
List<Line> result = new ArrayList<>();
for (int i = 0; i < grid.length; i++) {
result.add(row(grid, i));
result.add(column(grid, i));
}
result.add(rightDiagonal(grid));
result.add(leftDiagonal(grid, grid.length));
return result;
}
And a method to see who won in a line:
int getWinnerFromLine(Line line, int length) {
int first = line.get(0);
if (first == 0) return 0;
for (int i = 0; i < length; i++) {
if (line.get(i) != first) return 0;
}
return first;
}
Then finally it is easy to find out who won in the case of a draw, or zero if nobody won.
int getWinningPlayer(int[][] grid) {
List<Line> lines = makeLines(grid); // This could be created once at the start of the game.
for (Line line : lines) {
int winner = getWinnerFromLine(line, grid.length);
if (winner != 0) return winner;
}
return 0;
}