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 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 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,...
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...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating the average sightings from the Total Sightings array float calcAverage(float totalSightings[],int n) {    int i;    float sum=0.0;    for(i=0;i<n;i++)    sum=sum+totalSightings[i];    return sum/n; } int main() {    // n is no. of bird watchers    //flag , flag2 and flag3 are for validating using while loops    int n,i,flag,flag2,flag3;       //ch also helps in validating    char ch;   ...
write a java program to Implement a Priority Queue using a linked list. Include a main...
write a java program to Implement a Priority Queue using a linked list. Include a main method demonstrating enqueuing and dequeuing several numbers, printing the list contents for each.
Code in Java, Use both Set and TreeSet in only one main to show the differences...
Code in Java, Use both Set and TreeSet in only one main to show the differences between the Set and TreeSet that Set still remove the duplicate but won't sort the elements. Create a class named DictionaryWord as: DictionaryWord - word: String                                                              - meanings: String + DictionaryWord (String word, String meanings) + getWord(): String + setWord (String word): void + getMeanings(): String + setMeanings(String meanings): void Write a program with the following requirements: Creates 8 DictionaryWord objects with: Word...
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
Using the provided code (found here), write a program using the main method where the user...
Using the provided code (found here), write a program using the main method where the user enters Strings and the program echoes these strings to the console until the user enters “quit”. When user quits the program should print out, “Goodbye”. You may assume that the case is ignored when the user enters, “quit”, so “quit”, “QUIT”, “Quit”,“qUiT”, etc. are all acceptable ways to end the program. The results should be printed out to the console in the following format:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT