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&);/* * Complete the 'knightlOnAChessboard' function below. * * The function is expected to return a 2D_INTEGER_ARRAY. * The function accepts INTEGER n as parameter. */intbfs(inti,intj,intn){queue<pair<pair<int,int>,int>>q;intv[n][n];intmovesx[]={i,i,-i,-i,j,j,-j,-j};intmovesy[]={j,-j,j,-j,i,-i,i,-i};memset(v,-1,sizeof(v));q.push({{0,0},0});while(!q.empty()){intx=q.front().first.first,y=q.front().first.second,level=q.front().second;for(inti=0;i<8;i++){inttempx=x+movesx[i],tempy=y+movesy[i];if(tempx>=0&&tempy>=0&&tempx<n&&tempy<n&&v[tempx][tempy]==-1){q.push({{tempx,tempy},level+1});v[tempx][tempy]=1;}}if(x==n-1&&y==n-1){returnlevel;}q.pop();}return-1;}vector<vector<int>>knightlOnAChessboard(intn){vector<vector<int>>res(n-1,vector<int>(n-1,0));for(inti=0;i<n-1;i++){for(intj=0;j<n-1;j++){if(i==j){if((n+i)%(i+1)==0){res[i][j]=(n+i)/(i+1)-1;}else{res[i][j]=-1;}}if(res[i][j]==0&&i!=j)res[i][j]=bfs(i+1,j+1,n);res[j][i]=res[i][j];}}returnres;}intmain(){ofstreamfout(getenv("OUTPUT_PATH"));stringn_temp;getline(cin,n_temp);intn=stoi(ltrim(rtrim(n_temp)));vector<vector<int>>result=knightlOnAChessboard(n);for(size_ti=0;i<result.size();i++){for(size_tj=0;j<result[i].size();j++){fout<<result[i][j];if(j!=result[i].size()-1){fout<<" ";}}if(i!=result.size()-1){fout<<"\n";}}fout<<"\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;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
KnightL on a Chessboard
You are viewing a single comment's thread. Return to all comments →
c++ solution which worked for me
using bfs