# Minimum Passes Of Matrix

![](/files/A58YpJQ8pM5SDxnrw5EV)

*

```jsx
let converted = false;
function minimumPassesOfMatrix(m) {
  converted = false;
  
  // let minus = 0;
  let count = 0;
  do {
    const minus = convert(m);
    console.log({ converted, minus, count, m});
    
    if (converted === false) {
      return minus > 0 ? -1 : count;
    }
    
    count++;
  } while (true);

}

// O(m x n), O(n + m)
function convert(m) {
  converted = false;
  
  let minus = 0;
  let points = [];
  for (let i = 0; i < m.length; i++) {
    for (let j = 0; j < m[0].length; j++) {
      const curr = m[i][j];
      if (curr >= 0) continue;
      minus++;
      const flag = canConvertToPositive(m, i, j);
      if (flag === true) points.push([i, j]);
    }
  }

  for (const [x, y] of points) {
    m[x][y] *= -1;
    minus--;
    converted = true;
  }
  
  return minus;
}

function canConvertToPositive(m, i, j) {

  const down = i < m.length - 1 && m[i + 1][j] > 0;
  const up = i > 0 && m[i - 1][j] > 0;
  const right = j < m[0].length - 1 && m[i][j + 1] > 0;
  const left = j > 0 && m[i][j - 1] > 0;
  console.log({
    i,
    j,
    down,
    up,
    right,
    left
  })
  
  return down || up || right || left;
}

// Do not edit the line below.
exports.minimumPassesOfMatrix = minimumPassesOfMatrix;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/minimum-passes-of-matrix.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
