So I keep running into a problem with my code for checking if there is a connect 4 vertically. Preface to my code: the board has 6 rows and 7 columns, the variable player1 holds the value of the character being used as a chip and playerID just holds the value of whoever gets the connect 4.
public int verticalWin() {
int playerID = 0;
for (int x = 0; x < board[x].length; x++) {
int count = 1;
for (int y = board.length-2; y >= 0; y--) {
if (board[y][x] == board[y+1][x]) {
count++;
if (count == 4) {
if (board[y][x] == player1) {
playerID = 1;
} else {
playerID = 2;
}
}
} else {
count = 1;
}
}
}
return playerID;
}
The problem I keep running into is that an exception java.lang.ArrayIndexOutOfBoundsException: 6 keeps happening and I think it's in the first line, but I can't seem to find the problem.
Some cleaner code
boolean isWinnerOnColumn(int playerID, int column) {
int count = 0;
for (int row = 0; row < 6; row++) {
count = (board[row][column] == playerID) ? (count + 1) : 0;
if (count == 4){
return true;
}
}
return false;
}
public int verticalWin() {
for (int column = 0; column < 7; column++) {
if (isWinnerOnColumn(1, column) {
return 1;
}
if (isWinnerOnColumn(2, column) {
return 2;
}
}
return 0; // no winner
}
Related
This question already has an answer here:
Customizable TicTacToe game board with Java
(1 answer)
Closed 28 days ago.
Already implemented horizontal and vertical methods, i can't figure out diagonals
That's my working methods:
private boolean checkHorizontalWin(String gameBoard, int gameSize, int gameDifficulty) {
// CHECK HORIZONTAL WIN
for (int row = 0; row < gameSize; row++) {
char candidate = getPawnAtCoords(gameBoard, gameSize, row, 0);
int counter = 1;
for (int column = 0; column < gameSize; column++) {
char pawn = getPawnAtCoords(gameBoard, gameSize, row, column);
if ((pawn == candidate) && (pawn != '-')) {
counter++;
} else {
counter = 1;
candidate = pawn;
}
if (counter == gameDifficulty) {
return true;
}
}
}
return false;
}
private boolean checkHVerticalWin(String gameBoard, int gameSize, int gameDifficulty) {
// CHECK VERTICAL WIN
for (int column = 0; column < gameSize; column++) {
char candidate = getPawnAtCoords(gameBoard, gameSize, 0, column);
int counter = 1;
for (int row = 0; row < gameSize; row++) {
char pawn = getPawnAtCoords(gameBoard, gameSize, row, column);
if ((pawn == candidate) && (pawn != '-')) {
counter++;
} else {
counter = 1;
candidate = pawn;
}
if (counter == gameDifficulty) {
return true;
}
}
}
return false;
}
Anyone got an idea for diagonals?
Already tried everything what i can do by myself.
ChatGPT did it
private boolean checkDiagonalWin(String gameBoard, int gameSize, int gameDifficulty) {
// CHECK DIAGONAL WIN (LEFT TO RIGHT)
for (int row = 0; row < gameSize - gameDifficulty + 1; row++) {
for (int col = 0; col < gameSize - gameDifficulty + 1; col++) {
char candidate = getPawnAtCoords(gameBoard, gameSize, row, col);
int counter = 1;
for (int i = 1; i < gameDifficulty; i++) {
int nextRow = row + i;
int nextCol = col + i;
char pawn = getPawnAtCoords(gameBoard, gameSize, nextRow, nextCol);
if ((pawn == candidate) && (pawn != '-')) {
counter++;
} else {
counter = 1;
candidate = pawn;
}
if (counter == gameDifficulty) {
return true;
}
}
}
}
// CHECK DIAGONAL WIN (RIGHT TO LEFT)
for (int row = 0; row < gameSize - gameDifficulty + 1; row++) {
for (int col = gameSize - 1; col >= gameDifficulty - 1; col--) {
char candidate = getPawnAtCoords(gameBoard, gameSize, row, col);
int counter = 1;
for (int i = 1; i < gameDifficulty; i++) {
int nextRow = row + i;
int nextCol = col - i;
char pawn = getPawnAtCoords(gameBoard, gameSize, nextRow, nextCol);
if ((pawn == candidate) && (pawn != '-')) {
counter++;
} else {
counter = 1;
candidate = pawn;
}
if (counter == gameDifficulty) {
return true;
}
}
}
}
return false;
}
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I am making a tic tac toe game and one of the requirements is to have the game randomly decide who goes first. I assume I should be using Math.random() but I don't know how to implement it. If anyone can, please help adjust my code thanks :)
import java.util.Scanner;
public class TicTacToe
{
public static void main(String[] args)
{
Scanner console = new Scanner (System.in);
Game ticTacToe = new Game();
String no = "no";
System.out.println("~~~Tic Tac Toe~~~");
System.out.println("Would you like to play?");
String playerAnswer = console.nextLine();
while(!playerAnswer.equals(no))
{
ticTacToe.play();
System.out.println("Thanks for playing");
System.out.println("Would you like to play again? Press any key for yes, type no if you don't ");
playerAnswer=console.nextLine();
}
}
}
class Game
{
private final int empty = 0;
private final int player = 1;
private final int com = 2;
private final int size = 3;
private int[][] board;
public void printScreen()
{
int col;
int row;
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print(" " + (col+1));
}
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print("--");
}
System.out.println("-");
for (row = 0; row < size; row ++)
{
System.out.print((row+1) + "|");
for (col = 0; col < size; col ++)
{
if (board[row][col] == empty)
{
System.out.print(" ");
}
else if (board[row][col] == player)
{
System.out.print("X");
}
else if (board[row][col] == com)
{
System.out.print("O");
}
System.out.print("|");
}
System.out.println();
System.out.print(" ");
for (col = 0; col < size; col ++)
{
System.out.print("--");
}
System.out.println("-");
}
}
public void clear()
{
int col;
int row;
board = new int[size][size];
for (row = 0; row < size; row ++)
{
for (col = 0; col < size; col ++)
{
board[row][col] = empty;
}
}
}
public void computerMove()
{
int col;
int row;
int count;
int select;
count = 0;
for (row = 0; row < size; row ++)
for (col = 0; col < size; col ++)
if (board[row][col] == empty)
count ++;
select = (int) (Math.random() * count);
count = 0;
for (row = 0; row < size; row ++)
{
for (col = 0; col < size; col ++)
{
if (board[row][col] == empty)
{
if (count == select)
{
board[row][col] = com;
System.out.println("The computer selects row" + (row+1) + " column " + (col+1) + ".");
}
count ++;
}
}
}
}
public void playerMove()
{
Scanner console = new Scanner (System.in);
boolean a;
int col;
int row;
a = true;
while (a)
{
System.out.println("What is your move? Select a row number from 1 to " + size + " and a column number from 1 to " + size + ".");
row = console.nextInt();
col = console.nextInt();
if ((row < 1) || (row > size) || (col < 1) || (col > size))
{
System.out.println("Invalid choice, row " + row + " or column " + col + " must be from 1 to " + size + ".");
}
else
{
row --;
col --;
if (board[row][col] != empty)
{
System.out.println("That spot is already filled");
printScreen();
}
else
{
board[row][col] =player;
a = false;
}
}
}
}
public boolean checkWinner()
{
int col;
int row;
int count;
int win;
win = empty;
for (row = 0; row < size; row ++)
{
count = 0;
if (board[row][0] != empty)
for (col = 0; col < size; col ++)
if (board[row][0] == board[row][col])
count ++;
if (count == size)
win = board[row][0];
}
for (col = 0; col < size; col ++)
{
count = 0;
if (board[0][col] != empty)
for (row = 0; row < size; row ++)
if (board[0][col] == board[row][col])
count ++;
if (count == size)
win = board[0][col];
}
count = 0;
if (board[0][0] != empty)
for (row = 0; row < size; row ++)
if (board[0][0] == board[row][row])
count ++;
if (count == size)
win = board[0][0];
count = 0;
if (board[0][size-1] != empty)
for (row = 0; row < size; row ++)
if (board[0][size-1] == board[row][size-row-1])
count ++;
if (count == size)
win = board[0][size-1];
if (win != empty)
{
if (win == player)
System.out.println("Congratz you won");
else if(win == 3)
System.out.println("you lost");
return true;
}
count = 0;
for (row = 0; row < size; row ++)
for (col = 0; col < size; col ++)
if (board[row][col] == empty)
count ++;
if (count == 0)
{
System.out.println("Its a tie!");
return true;
}
return false;
}
public void play()
{
boolean e;
clear();
e=false;
while (!e)
{
printScreen();
playerMove();
printScreen();
e = checkWinner();
if (!e)
{
computerMove();
e = checkWinner();
if (e)
printScreen();
}
}
}
}
There may be many ways to do this including using a Random generator class, but as tic-tac only has two players, this can simply be done as getting a boolean
boolean player1Starts = (System.currentTimeMillis() % 2) == 0;
To implement this you would have to change your play method.
public void play()
{
boolean playerTurn = Math.random() <= .5
//this function returns a value between 0 an 1 exclusive
clear();
printScreen();
while (!checkWinner())
{
if (playerTurn) {
playerMove;
} else {
computerMove();
}
playerTurn = !playerTurn;
printScreen();
}
}
What this does is first determine if the player starts.
Then it clears and prints the empty board.
Then It loops through checking if there is a winner
If there isn't a winner we go into the loop and then if its the players turn they move else the computer moves
Then we update the playerTurn to be the opposite of what it was.
Then print the screen to see the move.
If there is a winner we exit the loop and finish the play method
I cannot get my write to file code working the error message- writeFile cannot be resolved. I a trying to write the board positions to a text file so the game can be saved. If the user chooses to save the game then it should call a new subroutine that will write the pieces to the file.
/*
* Skeleton program code for the AQA COMP1 Summer 2016 examination
* This code to be used in conjunction with the Preliminary Material
* written by the AQA Programmer Team
* Developed in the NetBeans 7.3.1. programming environment
* Additional classes AQAConsole2016, AQAReadTextFile2016 and
* AQAWriteTextFile2016 may be used.
*
* A package name may be chosen and private and public modifiers added -
* permission to make these changes to the Skeleton Program does not need
* to be obtained from AQA or the AQA Programmer
*/
import java.util.Random;
public class Aaa {
AQAConsole2016 console = new AQAConsole2016();
Random random = new Random();
int boardSize;
public Aaa() {
char choice;
String playerName;
// int boardSize;
boardSize = 6;
playerName = "";
do {
displayMenu();
choice = getMenuChoice(playerName);
switch (choice) {
case 'p' : playGame(playerName, boardSize);
break;
case 'e' : playerName = getPlayersName();
break;
case 'c' : boardSize = changeBoardSize();
break;
}
} while (choice != 'q');
}
void setUpGameBoard(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (row == (boardSize + 1) / 2 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2 + 1) {
board[row][column] = 'C';
} else {
if (row == (boardSize + 1) / 2 + 1 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2) {
board[row][column] = 'H';
} else {
board[row][column] = ' ';
}
}
}
}
}
int changeBoardSize() {
int boardSize;
do {
console.print("Enter a board size (between 4 and 9): ");
boardSize = console.readInteger("");
} while (!(boardSize >= 4 && boardSize <= 9));
return boardSize;
}
int getHumanPlayerMove(String playerName) {
int coordinates;
console.print(playerName + " enter the coordinates of the square where you want to place your piece: ");
coordinates = console.readInteger("");
return coordinates;
}
int getComputerPlayerMove(int boardSize) {
return ((random.nextInt(boardSize) + 1) * 10 + (random.nextInt(boardSize) + 1));
}
boolean gameOver(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == ' ')
return false;
}
}
return true;
}
String getPlayersName() {
String playerName;
console.print("What is your name? ");
playerName = console.readLine();
return playerName;
}
boolean checkIfMoveIsValid(char[][] board, int move) {
int row;
int column;
boolean moveIsValid;
row = move % 10;
column = move / 10;
moveIsValid = false;
if (((row<=boardSize) &&(row>0)) && ((column<=boardSize) && (column>0))){
if (board[row][column] == ' ') {
moveIsValid = true;
}
}
return moveIsValid;
}
int getPlayerScore(char[][] board, int boardSize, char piece) {
int score;
score = 0;
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == piece) {
score = score + 1;
}
}
}
return score;
}
boolean checkIfThereArePiecesToFlip(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipStillPossible;
boolean flipFound;
boolean opponentPieceFound;
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
flipStillPossible = true;
flipFound = false;
opponentPieceFound = false;
while (rowCount <= boardSize && rowCount >= 1 && columnCount >= 1 && columnCount <= boardSize && flipStillPossible && !flipFound ) {
if (board[rowCount][columnCount] == ' ') {
flipStillPossible = false;
} else {
if (board[rowCount][columnCount] != board[startRow][startColumn]) {
opponentPieceFound = true;
} else {
if (board[rowCount][columnCount] == board[startRow][startColumn] && !opponentPieceFound) {
flipStillPossible = false;
} else {
flipFound = true;
}
}
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
return flipFound;
}
void flipOpponentPiecesInOneDirection(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipFound;
flipFound = checkIfThereArePiecesToFlip(board, boardSize, startRow, startColumn, rowDirection, columnDirection);
if (flipFound) {
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
while (board[rowCount][columnCount] != ' ' && board[rowCount][columnCount] != board[startRow][startColumn]) {
if (board[rowCount][columnCount] == 'H') {
board[rowCount][columnCount] = 'C';
} else {
board[rowCount][columnCount] = 'H';
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
}
}
void makeMove(char[][] board, int boardSize, int move, boolean humanPlayersTurn) {
int row;
int column;
row = move % 10;
column = move / 10;
if (humanPlayersTurn) {
board[row][column] = 'H';
} else {
board[row][column] = 'C';
}
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, -1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, 1);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, -1);
}
void printLine(int boardSize) {
console.print(" ");
for (int count = 1; count <= boardSize * 2 - 1; count++) {
console.print("_");
}
console.println();
}
void displayGameBoard(char[][] board, int boardSize) {
console.println();
console.print(" ");
for (int column = 1; column <= boardSize; column++)
{
console.print(" ");
console.print(column);
}
console.println();
printLine(boardSize);
for (int row = 1; row <= boardSize; row++) {
console.print(row);
console.print(" ");
for (int column = 1; column <= boardSize; column++) {
console.print("|");
console.print(board[row][column]);
}
console.println("|");
printLine(boardSize);
console.println();
}
}
void displayMenu() {
console.println("(p)lay game");
console.println("(e)nter name");
console.println("(c)hange board size");
console.println("(q)uit");
console.println();
}
char getMenuChoice(String playerName) {
char choice;
console.print(playerName + " enter the letter of your chosen option: ");
choice = console.readChar();
return choice;
}
void playGame(String playerName, int boardSize) {
char[][] board = new char[boardSize + 1][boardSize + 1];
boolean humanPlayersTurn;
int move;
int humanPlayerScore;
int computerPlayerScore;
boolean moveIsValid;
setUpGameBoard(board, boardSize);
humanPlayersTurn = false;
int NoOfMoves=0;
do {
humanPlayersTurn = !humanPlayersTurn;
displayGameBoard(board, boardSize);
moveIsValid = false;
do {
if (humanPlayersTurn) {
move = getHumanPlayerMove(playerName);
} else {
move = getComputerPlayerMove(boardSize);
}
moveIsValid = checkIfMoveIsValid(board, move);
} while (!moveIsValid);
if (!humanPlayersTurn) {
NoOfMoves++;
console.println("The number of moves completed so far: " +NoOfMoves);
console.print("Press the Enter key and the computer will make its move");
console.readLine("");
}
makeMove(board, boardSize, move, humanPlayersTurn);
console.println();
String answer = console.readLine("Do you want to save the board? (y/n)");
if (answer.equalsIgnoreCase("y")){
writeBoard(board, boardSize);
console.println("Saved!");
}
} while (!gameOver(board, boardSize));
displayGameBoard(board, boardSize);
humanPlayerScore = getPlayerScore(board, boardSize, 'H');
computerPlayerScore = getPlayerScore(board, boardSize, 'C');
if (humanPlayerScore > computerPlayerScore) {
console.println("Well done, " + playerName + ", you have won the game!");
}
else {
if (humanPlayerScore == computerPlayerScore) {
console.println("that was a draw!");
} else {
console.println("The computer has won the game!");
}
console.println();
}
}
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
public static void main(String[] args) {
new Aaa();
}
}
This Section contains the errors:
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
The problematic section contains a variable named writeFile which can not be resolved. No where in the class Aaa that you have shared, neither this variable has been declared nor initialized with an instance of its type. So the method void writeBoard(char[][] board, int boardSize) gives compilation error.
From the usage of this variable it is clear that it belongs to a class which has following instance methods:
1) openFile(String filename)
2) writeToTextFile(String piece)
3) closeFile()
Please search the class which has the above methods and on finding create an instance of that as the first statement inside the method void writeBoard(char[][] board, int boardSize). Hope it helps.
My check vertical win and check horizontal win work perfectly fine, however i dont know what to do with my check diagonal code to make it actually check diagonal. Some guidance would be much appreciated and this is in java. Thank you.
private boolean checkVerticalWin()
{
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
System.out.println("check vert");
for(int j = 0; j < myNumColumns; j++)
{
for(int i = 0; i < myNumRows; i++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
if(count == 1)
{
myWinBegin = new Point(i,j);
}
}
else
{
myWinBegin = null;
count = 0;
}
System.out.println(count);
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
myWinBegin = null;
return false;
}
private boolean checkHorizontalWin()
{
System.out.println("test");
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
for(int i = 0; i < myNumRows; i++)
{
for(int j = 0; j < myNumColumns; j++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null)
{
count++;
if (count == 1)
{
myWinBegin = new Point(i,j);
}
}
else
{
myWinBegin = null;
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
myWinBegin = null;
return false;
}
private boolean checkDiagonalWin()
{
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
for(int i = 0; i < myNumRows; i++)
{
for (int j = 0; j < myNumColumns; j++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
myWinEnd = new Point(i,j);
}
if(count == myWinLength)
{
return true;
}
}
}
for(int j = 0; j < myNumColumns; j--)
{
for (int i = 0; i < myNumRows; i--)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
for(int j = 0; j < myNumColumns; j++)
{
for (int i = 0; i < myNumRows; i--)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
}
else
{
myWinBegin = new Point(i,j);
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
for(int j = 0; j < myNumColumns; j--)
{
for (int i = 0; i < myNumRows; i++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
return false;
}
So basically, you need a start point, you then need to determine in which direction to move
With that idea in hand, you could use something like...
boolean win = true;
for (int count = 0; count < 4; count++) {
if (row < myNumRows && row >= 0 && col < myNumColumns && col >= 0) {
int test = myBoard[row][col];
if (test != check) {
win = false;
break;
}
} else {
break;
}
row += rowDelta;
col += colDelta;
}
As the basic algorithm. All this does is checks each cell from a start point, to a total of 4 cells, the algorithm moves by the specified delta/direction and keeps checking while each cell matches the check value.
Now, I'd wrap this in a simple method
public boolean didWin(int[][] grid, int check, int row, int col, int rowDelta, int colDelta) {
boolean win = true;
for (int count = 0; count < 4; count++) {
if (row < ROWS && row >= 0 && col < COLUMNS && col >= 0) {
int test = grid[row][col];
if (test != check) {
win = false;
break;
} else {
break;
}
}
row += rowDelta;
col += colDelta;
}
return win;
}
which makes it simpler to call, know given any point, you can do something like...
int startRow = ...;
int startCol = ...;
int player = ...;
if (didWin(myBoard, player, startRow, startCol, 1, 0) || // Vertical, down
didWin(myBoard, 1, startRow, startCol, 0, 1) || // Right
didWin(myBoard, 1, startRow, startCol, 0, -1) || // Left
didWin(myBoard, 1, startRow, startCol, 1, 1) || // Right/down
didWin(myBoard, 1, startRow, startCol, -1, -1) || // Left/Up
didWin(myBoard, 1, startRow, startCol, 1, -1) || // Down/Left
didWin(myBoard, 1, startRow, startCol, -1, 1) // Up/Right
) {
// You be the winner
}
nb: I've left out check a vertical up direction, because it's unlikely that you could actually win this way
ps: I'd be even more lazy and would just have a didWin method, which did the above checks and returned true or false, but I'm lazy
So, the startRow and startCol would represent the anchor point around which you want to check and would, in this example, represent the last drop.
This example uses a int to represent the player/token, but you could use anything, all this does is compares the token you supply with the values in the array
i'm a bit stuck with the Sudoku algorithm, i coded it using backtrack, and following the theorical steps this should work, and i tried to debuge it, but is too hard (and yes, it solve some numbers and does things)
i paste the code, i hope that you can help me, i really can't see where the problem is...
public void backtracking(int row,int col){
if(row > 8){
System.out.println("Solution Found!!");
printSudoku();
}
if (m[row][col] != 0){
next(row, col);
}
else {
for(int i =1; i < n;i++)
if(row(row, i) && col(col, i)) {
m[row][col] =i;
next(row, col);
}
m[row][col] = 0;
}
}
public void next( int row, int col ) {
if( col < 8)
backtracking( row, col + 1 ) ;
else
backtracking( row+ 1, 0 ) ;
}
public boolean region(int x, int y, int numReg) {
x = (x / 3) * 3 ;
y = (y / 3) * 3 ;
for( int r = 0; r < 3; r++ )
for( int c = 0; c < 3; c++ )
if( m[x+r][y+c] == numReg )
return false ;
return true ;
}
public boolean row(int x, int k){
for(int i =0; i < 9; i++)
if(m[x][i] == k)
return false;
return true;
}
public boolean col(int x, int k){
for(int i =0; i < 9; i++)
if(m[i][x] == k)
return false;
return true;
}
I ommited the "printSudoku" method, is just a double for and you know.
The code seems almost right.
As far as i can see you just forgot to call the region method. And I can't see where the variable n is coming from.
Try it with this slightly modified backtracking method:
public static void backtracking(int row, int col) {
if (row > 8) {
System.out.println("Solution Found!!");
printSudoku();
System.exit(0); //exiting after solution is found
}
if (m[row][col] != 0) {
next(row, col);
} else {
for (int i = 1; i <= 9; i++) //replaced i < n with i<=9
if (row(row, i) && col(col, i) && region(row, col, i)) { //calling region method too
m[row][col] = i;
next(row, col);
}
m[row][col] = 0;
}
}