โš”๏ธ
DSA Important Questions
  • ๐Ÿ˜‡README
  • ๐Ÿ”ซQuestion List
  • ๐ŸงชFormula List
  • ๐Ÿ—’๏ธ01 Array
    • โœ…Rotate Matrix
    • โœ…Max Sum Contiguous Subarray
    • Find Duplicate in Array
    • โœ…Merge Intervals
    • โœ…Spiral Order Matrix I
    • Repeat and Missing Number Array
    • โœ…Merge Overlapping Intervals
    • โœ…Set Matrix Zeros
    • โœ…Spiral Order Matrix II
    • Largest Number
    • First Missing Integer
    • โœ…Pascal Triangle
    • โญMax Distance
    • โœ…Wavy Array
    • Next Permutation
    • โœ…Min Steps in Infinite Grid
    • Flip
    • โญFind Permutation
    • โญMaximum Absolute Difference
    • โญMaximum Unsorted Subarray
    • Reorder Data in Log File
    • โœ…Make equal elements Array
  • โž•02 Math
    • โœ…Excel Column Number
    • โญExcel Column Title
    • โญGrid Unique Paths
    • โญPower Of Two Integers
    • โœ…Next Similar Number
    • โญk-th Permutation
  • ๐Ÿ”03 Binary Search
    • โญMedian of Array
    • โญSquare Root of Integer
    • โญRotated Sorted Array Search
    • โญMatrix Median
    • Capacity To Ship Packages Within B Days
  • ๐Ÿงต04 String
    • Implement StrStr
    • โญInteger to Roman
    • โญRoman to Integer
    • Length of Last Word
    • โญatoi
    • โญValid IP Addresses
    • โญCompare Version Numbers
    • โญLongest Palindromic Substring
    • Count And Say
    • Reverse the String
    • Power of 2
    • ๐ŸšงKMP: Minimum Characters Required to Make a String Palindromic
    • โญConvert to Palindrome
    • Bulls and Cows
  • 1๏ธโƒฃ05 Bit Manipulation
    • Reverse Bits
    • Single Number
    • โญDivide Integers
    • โญSingle Number II
    • โญCount Total Set Bits
    • โญPalindromic Binary Representation
  • โœŒ๏ธ06 Two Pointers
    • Merge Two Sorted Lists II
    • โญ3 Sum
    • Remove Duplicates from sorted Array
    • โญContainer With Most Water
    • Remove Element from Array
    • โญMax Continuous Series of 1s
    • Pair With Given Difference
    • โญMaximum Ones After Modification
  • ๐Ÿ”—07 Linked List
    • Swap List Nodes in Pairs
    • Rotate List
    • โญReorder List
    • Merge Two Sorted Lists
    • Remove Duplicates from Sorted List
    • Add Two Numbers as Lists
    • Remove Nth Node from List End
    • โญList Cycle
    • Intersection of Linked Lists
    • โญReverse Linked List II
    • Palindrome List
    • โญK reverse linked list
    • โญReverse Alternate K Nodes
    • โญKth Node From Middle
    • โญSort Binary Linked List
    • โญEven Reverse
  • ๐Ÿ“š08 Stacks and Queues
    • โญRain Water Trapping
    • Generate all Parentheses
    • โญLargest Rectangle in Histogram
    • โญMin Stack
    • Redundant Braces
    • Nearest Smaller Element
    • โญFirst non-repeating character in a stream of characters
    • โœ…Balanced Parantheses!
  • ๐Ÿ”™09 Backtracking
    • โญKth Permutation Sequence
    • โญCombination Sum
    • Combination Sum II
    • โญNQueens
    • Combinations
    • โญSubsets II
    • Subset
    • Palindrome Partitioning
  • ๐Ÿ’ฑ10 Hashing
    • โญLongest Consecutive Sequence
    • โญ4 Sum
    • โญAnagrams
    • โญPoints on the Straight Line
    • 2 Sum
    • โญValid Sudoku
    • Copy List
    • Longest Substring Without Repeat
  • ๐Ÿ—ป11 Heaps & Maps
    • Merge K Sorted Lists
    • โญLRU Cache
    • โญInversions
    • Distinct Numbers in Window
  • ๐ŸŒณ12 Tree Data Structure
    • โœ…Inorder Traversal
    • โญRecover Binary Search Tree
    • โญInorder Traversal of Cartesian Tree
    • โญLeast Common Ancestor
    • โญConstruct Binary Tree From Inorder And Preorder
    • Flatten Binary Tree to Linked List
    • Valid Binary Search Tree
    • โœ…Preorder Traversal
    • โญBinary Tree From Inorder And Postorder
    • Balanced Binary Tree
    • โœ…Sorted Array To Balanced BST
    • Symmetric Binary Tree
    • โœ…Postorder Traversal
    • โญPopulate Next Right Pointers Tree
    • Identical Binary Trees
    • BST Iterator
    • ZigZag Level Order Traversal BT
    • Path Sum
    • Next Pointer Binary Tree
    • Min Depth of Binary Tree
    • Root to Leaf Paths With Sum
    • โญKth Smallest Element in Tree
    • โญ2-Sum Binary Tree
    • Vertical Order traversal of Binary Tree
    • โญDiagonal Traversal
    • Cousins in Binary Tree
    • Path to Given Node
    • Remove Half Nodes
    • Merge two Binary Tree
    • โญBurn a Tree
    • Nodes at Distance K
    • Vertical Sum of a Binary Tree
    • Covered / Uncovered Nodes
  • 13 Dynamic Programming
    • Ugly Number II
    • Coin Change
    • 0 - 1 Knapsack Problem
    • Permutation Coefficient
  • 14 Greedy Algorithm
    • โญGas Station
    • โญMajority Element
    • โญDistribute Candy
    • โญHighest Product
    • Assign Mice to Holes
    • โญMeeting rooms
  • ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ15 Graph
    • Clone Graph
    • Word Search Board
    • โญStepping Numbers
    • Black Shapes
    • Knight On Chess Board
    • โŒSmallest Multiple With 0 and 1
    • โญCommutable Islands
    • Possibility of finishing all courses given pre-requisites
    • โŒValid Path
    • Cycle in Directed Graph
    • โŒCycle in Undirected Graph
Powered by GitBook
On this page
  • Using BFS
  • Using Pair<int, int>
  • Using Coordinate Class
  1. 15 Graph

Black Shapes

PreviousStepping NumbersNextKnight On Chess Board

Last updated 2 years ago

Using BFS

Using Pair<int, int>

// adding these deltas to i and j 
// moves them up-down and left-right respectively.
int xDelta[4] = {0, 0, -1, 1};
int yDelta[4] = {-1, 1 , 0, 0};

class Coordinate {
  public:
    int i;
    int j;
    
    Coordinate(int i, int j) {
        this->i = i;
        this->j = j;
    }
};

// checks if (i, j) is a valid index for the matrix A
bool isBounded(int i, int j, vector<string> &A) {
    if(i < 0 || j < 0 || i >= A.size() || j >= A[0].size())
        return false;
    return true;
}

int Solution::black(vector<string> &A) {
    // Step 1: untill each cell have been traversed, find an X
    // Step 2: increment the count of shapes
    // Step 3: remove all adjacent Xs
    // Step 4: go to step 1
    
    // set count initially to 0
    int count = 0;
    
    // travese each cell
    for(int i = 0; i < A.size(); i++)
        for(int j = 0; j < A[0].size(); j++)
            // if the cell is  an X
            if(A[i][j] == 'X') {
                // increment the count since an unvisited bunch of X is here
                count++;
                
                // create a queue of pair of (i, j)
                queue<Coordinate> q;
                
                // insert current cell containing X
                q.push(Coordinate(i, j));
                A[i][j] = 'O';
                
                // untill all Xs have been removed
                while(!q.empty()) {
                    // current size of queue
                    int size = q.size();
                    // process all the elements currently in queue
                    for(int i = 1; i <= size; i++) {
                        // get front cell
                        Coordinate frontCell = q.front();
                        // remove it fron the queue
                        q.pop();                        
                                                
                        // use xDelta and yDelta to get all 4 neighbours
                        for(int dir = 0; dir < 4; dir++) {
                            
                            int nextI = frontCell.i + xDelta[dir];
                            int nextJ = frontCell.j + yDelta[dir];
                            
                            // check if neighbour index are in bounds
                            // and that they contain X
                            if(isBounded(nextI, nextJ, A) && A[nextI][nextJ] == 'X')  {
                                
                                // if so then push them into the queue for having its neighbours checked
                                q.push(Coordinate(nextI, nextJ));    
                                
                                // PROCESSING: 
                                // remove X and replace with O
                                A[nextI][nextJ] = 'O';
                            }
                        }
                        
                    }
                }
            }
    
    // return the count
    return count;
    
}

Using Coordinate Class

class Coordinate {
  public:
    int i;
    int j;
    
    Coordinate(int i, int j) {
        this->i = i;
        this->j = j;
    }
    
    // checks if (i, j) is a valid index for the matrix A
    bool isBounded(vector<string> &A) {
        if(i < 0 || j < 0 || i >= A.size() || j >= A[0].size())
            return false;
        return true;
    }
    
    // get neighbours of i, j
    vector<Coordinate> getNeighbours() {
        // adding these deltas to i and j 
        // moves them up-down and left-right respectively.
        int xDelta[4] = {0, 0, -1, 1};
        int yDelta[4] = {-1, 1 , 0, 0};
        
        // Resulting neighbours contains four negihbours in four directions
        vector<Coordinate> neighbours;
        
        // loop to get delta
        for(int dir = 0; dir < 4; dir++) 
            // craete a neighbour using delta and 
            // push it into result
            neighbours.push_back(Coordinate(i + xDelta[dir], j + yDelta[dir]));
        
        return neighbours;
    }
};

int Solution::black(vector<string> &A) {
    // Step 1: untill each cell have been traversed, find an X
    // Step 2: increment the count of shapes
    // Step 3: remove all adjacent Xs
    // Step 4: go to step 1
    
    // set count initially to 0
    int count = 0;
    
    // travese each cell
    for(int i = 0; i < A.size(); i++)
        for(int j = 0; j < A[0].size(); j++)
            // if the cell is  an X
            if(A[i][j] == 'X') {
                // increment the count since an unvisited bunch of X is here
                count++;
                
                // create a queue of pair of (i, j)
                queue<Coordinate> q;
                
                // insert current cell containing X
                q.push(Coordinate(i, j));
                A[i][j] = 'O';
                
                // untill all Xs have been removed
                while(!q.empty()) {
                    // current size of queue
                    int size = q.size();
                    // process all the elements currently in queue
                    for(int i = 1; i <= size; i++) {
                        // get front cell
                        Coordinate frontCell = q.front();
                        // remove it fron the queue
                        q.pop();                        
                            
                        // get neighbours and process them            
                        for(Coordinate neighbour: frontCell.getNeighbours()) {
                            // check if neighbour is bounded and contain X
                            if(neighbour.isBounded(A) && A[neighbour.i][neighbour.j] == 'X') {
                                // if so then push it into the queue for having its neighbours processed
                                q.push(neighbour);
                                
                                // PROCESSING:
                                // Replace X with O
                                A[neighbour.i][neighbour.j] = 'O';                                
                            }
                        }   
                    }
                }
            }
    
    // return the count
    return count;    
}
Without Comments
class Coordinate {
  public:
    int i;
    int j;
    
    Coordinate(int i, int j) {
        this->i = i;
        this->j = j;
    }
    
    bool isBounded(vector<string> &A) {
        if(i < 0 || j < 0 || i >= A.size() || j >= A[0].size())
            return false;
        return true;
    }
    
    vector<Coordinate> getNeighbours() {
        int xDelta[4] = {0, 0, -1, 1};
        int yDelta[4] = {-1, 1 , 0, 0};
        
        vector<Coordinate> neighbours;
        
        for(int dir = 0; dir < 4; dir++) 
            neighbours.push_back(
                        Coordinate(i + xDelta[dir], j + yDelta[dir])
                                );
        
        return neighbours;
    }
};

int Solution::black(vector<string> &A) {
    int count = 0;
    
    for(int i = 0; i < A.size(); i++)
        for(int j = 0; j < A[0].size(); j++)
            if(A[i][j] == 'X') {
                count++;
                
                queue<Coordinate> q;
                
                q.push(Coordinate(i, j));
                A[i][j] = 'O';
                
                while(!q.empty()) {
                    int size = q.size();
                    for(int i = 1; i <= size; i++) {
                        Coordinate frontCell = q.front();
                        q.pop();                        
                            
                        for(Coordinate neighbour: frontCell.getNeighbours()) {
                            if(neighbour.isBounded(A) 
                                    && A[neighbour.i][neighbour.j] == 'X') {
                                q.push(neighbour);
                                
                                A[neighbour.i][neighbour.j] = 'O';                                
                            }
                        }   
                    }
                }
            }
    
    return count;
    
}
๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ
Black Shapes - InterviewBitInterviewBit
Logo