0
Good afternoon. I made the challenge of Queen’s Attack (I started programming a few days ago) and I can’t get 100% approval on this challenge. It’s said that my code needs to be optimized, but I don’t know how to do that. I know that the same is long and in some repetitive moments, but did not know how to improve the same.
public static int queensAttack(int n, int k, int r_q, int c_q, List<List<int>> obstacles)
{
int nbmrOfMoves = 0;
bool shouldBreak = false;
for(int i = 1; i < n; i++){
for(int x = 0; x<k; x++){
if(r_q + i == obstacles[x][0] && c_q == obstacles[x][1]){
shouldBreak = true;
}
}
if(shouldBreak == true){
break;
}
if(r_q + i <= n){
nbmrOfMoves++;
}
}
shouldBreak = false;
for(int i = 1; i < n; i++){
for(int x = 0; x<k; x++){
if(r_q - i == obstacles[x][0] && c_q == obstacles[x][1]){
shouldBreak = true;
}
}
if(shouldBreak == true){
break;
}
if(r_q - i > 0){
nbmrOfMoves++;
}
}
shouldBreak = false;
for(int i = 1; i < n; i++){
for(int x = 0; x<k; x++){
if(r_q == obstacles[x][0] && c_q - i == obstacles[x][1]){
shouldBreak = true;
}
}
if(shouldBreak == true){
break;
}
if(c_q - i >0){
nbmrOfMoves++;
}
}
shouldBreak = false;
for(int i = 1; i < n; i++){
for(int x = 0; x<k; x++){
if(r_q == obstacles[x][0] && c_q + i == obstacles[x][1]){
shouldBreak = true;
}
}
if(shouldBreak == true){
break;
}
if(c_q + i <= n){
nbmrOfMoves++;
}
}
shouldBreak = false;
for (int i = 1; i < n; i++){
for(int x = 0; x < k; x++){
if(r_q + i == obstacles[x][0] && c_q + i == obstacles[x][1]){
shouldBreak = true;
}
}
if(shouldBreak == true){
break;
}
if(r_q + i <= n && c_q + i <= n){
nbmrOfMoves++;
}
}
shouldBreak = false;
for (int i = 1; i < n; i++){
for(int x = 0; x < k; x++){
if(r_q - i == obstacles[x][0] && c_q + i == obstacles[x][1]){
shouldBreak = true;
}
}
if(shouldBreak == true){
break;
}
if(r_q - i > 0 && c_q + i <= n){
nbmrOfMoves++;
}
}
shouldBreak = false;
for (int i = 1; i < n; i++){
for(int x = 0; x < k; x++){
if(r_q + i == obstacles[x][0] && c_q - i == obstacles[x][1]){
shouldBreak = true;
}
}
if(shouldBreak == true){
break;
}
if(r_q + i <= n && c_q - i > 0){
nbmrOfMoves++;
}
}
shouldBreak = false;
for (int i = 1; i < n; i++){
for(int x = 0; x < k; x++){
if(r_q - i == obstacles[x][0] && c_q - i == obstacles[x][1]){
shouldBreak = true;
}
}
if(shouldBreak == true){
break;
}
if(r_q - i > 0 && c_q - i > 0){
nbmrOfMoves++;
}
}
return nbmrOfMoves;
}
}
In my opinion these "challenge" sites are not good for those who are starting, because their goal is not to actually teach. There is no teaching and they do not even say what is wrong (and then how will someone learn?). Of course others may disagree, but for those who are starting I think this site can even be harmful. Anyway, if you started programming a few days ago, I suggest you first learn the basics (programming logic, algorithms, data structures) and then try more complicated things
– hkotsubo