0

Position of "-1".

In the given NxM matrix find the LAST position of the minus one(-1). If it will be no "-1" value in the given matrix just output "-1 -1".

Input First line N and M (1<=N,M<=100). Then NxM table is given(all number are integers)

Output First number have to be the row number,and then column number of last "-1" element.

Here is my solution. But I have wrong answer.

#include <iostream>
#include <climits>
using namespace std;

int main () {
    int row, col;
    double x = 0, y = 0;
    cin >> row >> col;
    int matrix[row][col];
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            cin >> matrix[i][j];
            if (matrix[i][j] < 0) {
                x = i + 1;
                y = j + 1;
            }

        }
    }
    if (x == 0 && y == 0)
        x = -1, y = -1;
    cout << x << " " <<y;
}
Dddddd
  • 21

1 Answers1

0

Some potential problems:

  • if (matrix[i][j] < 0) does not check for -1 only. Any negative value will make that condition true.
  • Unless explicitly specified, I would assume that they want the coordinates with a 0-base, not a 1-base, which would make x = i + 1; and y = j + 1; wrong.
  • cout << x << " " <<y; is confusing - but you seem to have assigned the row to x and the column to y so I guess it would work if the condition and assignments above were ok.
  • int matrix[row][col]; is not standard C++. A standard version would be std::vector<std::vector<int>> matrix(row, std::vector<int>(col));

... but - since you only need to print the last position where a -1 is entered, you don't need to store the whole array.

Just read the numbers one by one and check if the entered number is -1. If it is, store the position.

Example:

#include <iostream>

int main () {
    int row, col;
    int x = -1, y = -1; // if no -1 is found, these will still be -1

    if(!(std::cin >> row >> col) || row < 1 || col < 1) return 1;
    
    int value;

    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            if(!(std::cin >> value)) return 1;

            if(value == -1) { // -1 entered, store the position
                y = i;
                x = j;                
            }
        }
    }

    std::cout << y << ' ' << x << '\n';
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108