Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Help!!!!!! Sudoku?? 10points! Java Problem!?

This a matrix/ part sudoku can someone help me on how to make an input on this or should I just start all over again?

import java.io.*;

public class Soduko {

public static void main(String[] args) {

int[][] matrix = parseProblem(args);

writeMatrix(matrix);

if (solve(0,0,matrix)) // solves in place

writeMatrix(matrix);

else

System.out.println("");

}

static boolean solve(int i, int j, int[][] cells) {

if (i == 9) {

i = 0;

if (++j == 9)

return true;

}

if (cells[i][j] != 0) // skip filled cells

return solve(i+1,j,cells);

for (int val = 1; val <= 9; ++val) {

if (legal(i,j,val,cells)) {

cells[i][j] = val;

if (solve(i+1,j,cells))

return true;

}

}

cells[i][j] = 0; // reset on backtrack

return false;

}

static boolean legal(int i, int j, int val, int[][] cells) {

for (int k = 0; k < 9; ++k) // row

if (val == cells[k][j])

return false;

for (int k = 0; k < 9; ++k) // col

if (val == cells[i][k])

return false;

int boxRowOffset = (i / 3)*3;

int boxColOffset = (j / 3)*3;

for (int k = 0; k < 3; ++k) // box

for (int m = 0; m < 3; ++m)

if (val == cells[boxRowOffset+k][boxColOffset+m])

return false;

return true; // no violations, so it's legal

}

static int[][] parseProblem(String[] args) {

int[][] problem = new int[9][9]; // default 0 vals

for (int n = 0; n < args.length; ++n) {

int i = Integer.parseInt(args[n].substring(0,1));

int j = Integer.parseInt(args[n].substring(1,2));

int val = Integer.parseInt(args[n].substring(2,3));

problem[i][j] = val;

}

return problem;

}

static void writeMatrix(int[][] solution) {

for (int i = 0; i < 9; ++i) {

if (i % 3 == 0)

System.out.println(" -----------------------");

for (int j = 0; j < 9; ++j) {

if (j % 3 == 0) System.out.print("| ");

System.out.print(solution[i][j] == 0

? " "

: Integer.toString(solution[i][j]));

System.out.print(' ');

}

System.out.println("|");

}

System.out.println(" -----------------------");

}

}

1 Answer

Relevance
  • 1 decade ago
    Favorite Answer

    It seems you've got to feed arguments in this formatting:

    192

    391

    302

    ...

    where 192 means row 1 col 9 (or col 1 row 9, not sure), contains the number 2

Still have questions? Get your answers by asking now.