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...
Code using JAVA: must include "Main Method" for IDE testing! /** * Definition for a binary...
Code using JAVA: must include "Main Method" for IDE testing! /** * 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 TreeNode searchBST(TreeNode root, int val) {    }...
Code using JAVA: must include "Main Method" for IDE testing! /** * Definition for a binary...
Code using JAVA: must include "Main Method" for IDE testing! /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) {    } }; Given an array where elements are sorted in...
Code using JAVA: must include "Main Method" for IDE testing! /** * Definition for a binary...
Code using JAVA: must include "Main Method" for IDE testing! /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) {    } }; Given the root of a binary tree, return...
Code using JAVA: must include "Main Method" for IDE testing! /** * Definition for a binary...
Code using JAVA: must include "Main Method" for IDE testing! /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) {    } }; Given the root of a binary tree, return...
This code must be written in Java. This code also needs to include a package and...
This code must be written in Java. This code also needs to include a package and a public static void main(String[] args) Write a program named DayOfWeek that computes the day of the week for any date entered by the user. The user will be prompted to enter a month, day, and year. The program will then display the day of the week (Sunday..Saturday). The following example shows what the user will see on the screen: This program calculates the...
--- 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...
Java Class Create a class with a main method. Write code including a loop that will...
Java Class Create a class with a main method. Write code including a loop that will display the first n positive odd integers and compute and display their sum. Read the value for n from the user and display the result to the screen.
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT