Queen's Attack II Discussions | Algorithms | HackerRank
We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<bits/stdc++.h>usingnamespacestd;stringltrim(conststring&);stringrtrim(conststring&);vector<string>split(conststring&);/* * Complete the 'queensAttack' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER n * 2. INTEGER k * 3. INTEGER r_q * 4. INTEGER c_q * 5. 2D_INTEGER_ARRAY obstacles */intqueensAttack(intn,intk,intr_q,intc_q,vector<vector<int>>obstacles){// Directions: {row offset, col offset}vector<pair<int,int>>directions={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{-1,1},{1,-1},{1,1}};// Store obstacles for O(1) lookupset<pair<int,int>>obs;for(auto&o:obstacles){obs.insert({o[0],o[1]});}intattackableSquares=0;// Check each directionfor(auto&dir:directions){intr=r_q+dir.first;intc=c_q+dir.second;while(r>=1&&r<=n&&c>=1&&c<=n&&obs.find({r,c})==obs.end()){attackableSquares++;r+=dir.first;c+=dir.second;}}returnattackableSquares;}intmain(){ofstreamfout(getenv("OUTPUT_PATH"));stringfirst_multiple_input_temp;getline(cin,first_multiple_input_temp);vector<string>first_multiple_input=split(rtrim(first_multiple_input_temp));intn=stoi(first_multiple_input[0]);intk=stoi(first_multiple_input[1]);stringsecond_multiple_input_temp;getline(cin,second_multiple_input_temp);vector<string>second_multiple_input=split(rtrim(second_multiple_input_temp));intr_q=stoi(second_multiple_input[0]);intc_q=stoi(second_multiple_input[1]);vector<vector<int>>obstacles(k);for(inti=0;i<k;i++){obstacles[i].resize(2);stringobstacles_row_temp_temp;getline(cin,obstacles_row_temp_temp);vector<string>obstacles_row_temp=split(rtrim(obstacles_row_temp_temp));for(intj=0;j<2;j++){intobstacles_row_item=stoi(obstacles_row_temp[j]);obstacles[i][j]=obstacles_row_item;}}intresult=queensAttack(n,k,r_q,c_q,obstacles);fout<<result<<"\n";fout.close();return0;}stringltrim(conststring&str){strings(str);s.erase(s.begin(),find_if(s.begin(),s.end(),not1(ptr_fun<int,int>(isspace))));returns;}stringrtrim(conststring&str){strings(str);s.erase(find_if(s.rbegin(),s.rend(),not1(ptr_fun<int,int>(isspace))).base(),s.end());returns;}vector<string>split(conststring&str){vector<string>tokens;string::size_typestart=0;string::size_typeend=0;while((end=str.find(" ",start))!=string::npos){tokens.push_back(str.substr(start,end-start));start=end+1;}tokens.push_back(str.substr(start));returntokens;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Queen's Attack II
You are viewing a single comment's thread. Return to all comments →