Ticker

6/recent/ticker-posts

leetcode-3274 Check if Two Chessboard Squares Have the Same Color

 


in this problem there give two strings let take two strings names as 's' and 't' there is chess board the string s is a one box number of the chess board and the t is anther box number in same chess board the color of both string s&t is same we need to return true other wise return false

input: s="a1" and t="c3"

output: true

explanation: a1(black color)  c3(black color)

input 2: s="a1" and t="h3"

output: false

explanation: a1(black color)  h3(while color)

in this we discuss how to solve this problem i



In this we observed care fully we find the pattern in the problem total alphabets are 8 there are (a,b,c,d,e,f,g,h) on x - axis and numbers are 8 in y-axis in the chess board there are two colors (black, white) we want return true when two strings (s and t) have same color of box other wise return false there are odd numbers 



in above there is such  possibilitys a1 and b2 and a1 and c3 like that 



CODE:

class Solution {
public:
bool checkTwoChessboards(string s,string t) {
        int n=s.size();
        int m=s[1]-'0';
        int k=t[1]-'0';
        int dif=t[0]-s[0]-1;
        if(dif%2!=0){
           if(k%2!=0&&m%2!=0){
            return true;
           }
           if(k%2==0&&m%2==0){
            return true;
           }
        }
        else{
         if(dif%2==0){
            if(m%2!=0&&k%2==0){
                return true;
            }
            if(m%2==0&&k%2!=0){
                return true;
            }
         }
        }
        return false;
    }
};

explination:

in there problem statement there given two a strings s and t in both of them there is second position of the string is number "a1" here 1 is the number but its in the string how to convert string to number we know the convertion i already told previous posts  there two possible to convert first one is stoi   and second one is using ASCII values we convert by substracing the -'0' to that value like this we convert it
int k= s[1] - '0' ; in this k will store the number in string here the numbers in string is only single numbers there 8 only so no need for extra thinking like that target also we store in one integer to find the same color or not there is pattern in the problem a,c,e,g are the even numbers when we count front from 1(a),3(c),5(e),7(g) and there second position number in strings both are same like when that numbers in both strings divisible by %2 either both are non divisible by % 2 its true(both have same colors) when it one number is divisible and another number is non divisible % 2 its false condition
here when there are alphabets both are odd like this even also like this process only when it comes for odd and even in string 

Also Read

Post a Comment

0 Comments