Question

In: Computer Science

Code using JAVA: must include a "Main Method" to run on "intelliJ". Hint: Use a hash...

Code using JAVA:

must include a "Main Method" to run on "intelliJ".

Hint: Use a hash table. You can use either Java HashTable or Java HashMap. Refer to Java API for the subtle differences between HashTable and HashMap.

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

class Solution {
public boolean isValidSudoku(char[][] board) {
  
}
}

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.

Example 1:

Input: board = 
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true

Example 2:

Input: board = 
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Constraints:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit or '.'.

Solutions

Expert Solution

Below is the Java code:

import java.util.*;


class Solution {
    public boolean isValidSudoku(char[][] board) {
        HashMap<Integer,ArrayList<Character>> rmap=new HashMap<Integer,ArrayList<Character>>();
                HashMap<Integer,ArrayList<Character>> cmap=new HashMap<Integer,ArrayList<Character>>();

                for (int i = 0; i < 9; i++) {           // Put all keys in map
                    rmap.put (i, new ArrayList<Character>());
                    cmap.put (i, new ArrayList<Character>());
                }

                for (int i = 0; i < 9; i++)
                    for (int j = 0; j < 9; j++) {
                        if (board[i][j] == '.') continue;
                        Character val = board[i][j];
                        if (rmap.get(i).contains (val))   // Row already contains this value
                            return false;
                        else
                            rmap.get (i).add (val);

                        if (cmap.get(j).contains (val))   // Column already contains this value
                            return false;
                        else
                            cmap.get (j).add (val);
                    }


        // Now check for the 3 x 3 matrices and confirm if there are no duplicates
        for (int k = 0; k < 9; k++) {
            // Starting elements of 3 x 3 matrices are 00, 03, 06, 30, 33, 36, 60, 63, 66
            int i = 3 * (k / 3);   
            int j = 3 * (k % 3);
            char [] temp = {board [i][j], board [i][j+1], board [i][j+2], 
                            board [i+1][j], board [i+1][j+1], board [i+1][j+2], 
                            board [i+2][j], board [i+2][j+1], board [i+2][j+2] };
            if (!isValidSetOf9 (temp))
                return false;
        }
        return true;
    }
    
    private boolean isValidSetOf9 (char[] set9) {
        // Use similar technique as isValidSudoku but apply to one dimensional array of 9 elements
         HashMap<Integer,ArrayList<Character>> map=new HashMap<Integer,ArrayList<Character>>();
                 map.put (1, new ArrayList<Character>());   
                for (int i = 0; i < 9; i++) {
                    if (set9[i] == '.') continue;
                Character val = set9[i];
                if (map.get(1).contains (val))
                    return false;
                else
                    map.get (1).add (val);
                }
                return true;
    }
}

A main method to test:


public class Main
{
        public static void main(String[] args) {
            
            char [][] matrix = 
            {{'5','3','.','.','7','.','.','.','.'}
        ,{'6','.','.','1','9','5','.','.','.'}
        ,{'.','9','8','.','.','.','.','6','.'}
        ,{'8','.','.','.','6','.','.','.','3'}
        ,{'4','.','.','8','.','3','.','.','1'}
        ,{'7','.','.','.','2','.','.','.','6'}
        ,{'.','6','.','.','.','.','2','8','.'}
        ,{'.','.','.','4','1','9','.','.','5'}
        ,{'.','.','.','.','8','.','.','7','9'}};


        Solution s = new Solution ();
        if (s.isValidSudoku (matrix))
            System.out.println ("Yes");
        else
            System.out.println ("No");

        }
}

Related Solutions

Code using JAVA: must include a "Main Method" to run on "intelliJ". Hint: Use recursion "...
Code using JAVA: must include a "Main Method" to run on "intelliJ". Hint: Use recursion " /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isSymmetric(TreeNode...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; // constants const int FINAL_POSITION = 43; const int INITIAL_POSITION = -1; const int NUM_PLAYERS = 2; const string BLUE = "BLUE"; const string GREEN = "GREEN"; const string ORANGE = "ORANGE"; const string PURPLE = "PURPLE"; const string RED = "RED"; const string YELLOW = "YELLOW"; const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW}; const int NUM_COLORS = 6; // names...
Write a Java test program, all the code should be in a single main method, that...
Write a Java test program, all the code should be in a single main method, that prompts the user for a single character. Display a message indicating if the character is a letter (a..z or A..Z), a digit (0..9), or other. Java's Scanner class does not have a nextChar method. You can use next() or nextLine() to read the character entered by the user, but it is returned to you as a String. Since we are only interested in the...
In Java Create a class called "TestZoo" that holds your main method. Write the code in...
In Java Create a class called "TestZoo" that holds your main method. Write the code in main to create a number of instances of the objects. Create a number of animals and assign a cage and a diet to each. Use a string to specify the diet. Create a zoo object and populate it with your animals. Declare the Animal object in zoo as Animal[] animal = new Animal[3] and add the animals into this array. Note that this zoo...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char plain[50], cipher[50]="", decrypt[50]=""; int subkeys[50], len;       cout<<"Enter the plain text:"<<endl; cin>>plain;    cout<<"Enter the first subkey:"<<endl; cin>>subkeys[0];    _strupr(plain);    len = strlen(plain);    /**********Find the subkeys**************/    for(int i=1; i<len; i++) { if ((plain[i-1]>='A') && (plain[i-1]<='Z')) { subkeys[i] = plain[i-1]-65; } }    /****************ENCRYPTION***************/       for(int i=0; i<len; i++) { if ((plain[i]>='A') && (plain[i]<='Z')) {    cipher[i] = (((plain[i]-65)+subkeys[i])%26)+65; }...
IN JAVA: Build a class called ExamPractice from scratch. This class should include a main method...
IN JAVA: Build a class called ExamPractice from scratch. This class should include a main method that does the following: Prompt the user to enter a number of inches Read the number of inches entered from the console Convert the inches into an equivalent number of miles, yards, feet, and inches. Output the results to the console. For example, if a user entered 100000 inches, the program would output: 100000 inches is equivalent to: Miles: 1 Yards: 1017 Feet: 2...
Solve problem 2.3 (a, b) using Lagrangian Method. Hint: if you use the Lagrangian method, problem...
Solve problem 2.3 (a, b) using Lagrangian Method. Hint: if you use the Lagrangian method, problem 2.3 will be as follows. If X denotes the number of CDs and Y denotes the number of DVDs: Using the Lagrangian multiplier method, determine the values of X and Y that maximize the value of the function   U=(X^0.5)(Y^0.5)   subject to 200=5X+20Y Thus, problem II asks to solve followings : Max U=(X^0.5)(Y^0.5) s.t.    200= 5X +20Y
in netbeans using Java Create a project and a class with a main method, TestCollectors. ☑...
in netbeans using Java Create a project and a class with a main method, TestCollectors. ☑ Add new class, Collector, which has an int instance variable collected, to keep track of how many of something they collected, another available, for how many of that thing exist, and a boolean completist, which is true if we want to collect every item available, or false if we don't care about having the complete set. ☑ Add a method addToCollection. In this method,...
Using JAVA 2. A run is a sequence of adjacent repeated values. Write a code snippet...
Using JAVA 2. A run is a sequence of adjacent repeated values. Write a code snippet that generates a sequence of 20 random die tosses in an array and that prints the die values, marking the runs by including them in parentheses, like this: 1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 (3 3) Use the following pseudocode: inRun = false for each valid index i in the array If...
Language: Java Create a TryIt.java program with a main method. You are going to use this...
Language: Java Create a TryIt.java program with a main method. You are going to use this program to demonstrate some things about how Java works. Make your methods here private, because they are not intended to be called from outside the program. For each test below, make sure that you print to the console: 1) What is being tested 2) The desired output 3) The actual output Question to be answered: Should you use == or the String method equals...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT