There is a task:

On the chessboard of N x N dimension there are pawns and a knight. Determine the number of pawns that are under the knight’s battle with a given arrangement of pieces. Pawns in the array are marked as 1, knight - 2, free cell - 0.

Sample input:

5 1 0 0 0 0 0 0 0 1 0 0 2 0 0 1 0 0 0 1 0 1 0 1 0 0 

Sample output:

 5 

The question has nothing to do with the code, please help understand how this can be done. Hint who has suggestions, please. As I understand it, after initialization, you need to view the coordinates of the current cell and compare it with the previously created array of broken cells. How then to fill it? Confusion in the head. Can take the coordinate of each horse and compare it eight times with the "bat" coordinate?

  • 2
    Need to calculate in one move or several? - entithat pm
  • one
    Then you just need to consider the field as a two-dimensional array and check every move with the letter G of the knight for the presence of a pawn. - entithat
  • one
    It's easier to check 8 times, it seems to me it will not be easier. - entithat 1:27 pm
  • one
    @Max what language do you work? - Harry
  • one
    @Harry Olympiad C ++ - Max 1:31 pm

1 answer 1

there are pawns and a knight

If there is no ochepyatka and a horse is really one - then you just need to find all 8 cells under the fight (of course, with a check for going beyond the board), and see what's in them - if 1, then increment the counter :)

We get O (1).

If there are a lot of those and others, then I would read when I read who was less and play from them. But at the same time there is a subtlety - one pawn can be under the fight with several knights.

C ++ approximately

 int N, knightR, knightC; cin >> N; vector<vector<int>> board(N,vector<int>(N,0)); for(int row = 0; row < N; ++row) for(int col = 0; col < N; ++col) { cin >> board[row][col]; if (board[row][col] == 2) { knightR = row; knightC = col; } } int dr[] = { -2, -2, -1, -1, 1, 1, 2, 2 }; int dc[] = { -1, 1, 2, -2, 2, -2, 1, -1 }; int count = 0; for(int i = 0; i < 8; ++i) { int r = knightR+dr[i]; int c = knightC+dc[i]; if (r < 0 || r >= N || c < 0 || c >= N) continue; if (board[r][c] == 1) count++; } cout << count << endl; 
  • one
    Well, still need to find a horse) - yolosora
  • one
    @yolosora And you still read all the board fields - what is there to look for? 8- \ See when the two read? - Harry
  • @Harry count 8 dead coordinates? - Max
  • one
    @Harry, by the way, if the horse is single, then it is not necessary to read all the board's fields: D - yolosora pm
  • one
    @yolosora In principle - perhaps yes. But it will be harder than to read everything and not suffer :) - Harry