# 1536. Minimum Swaps to Arrange a Binary Grid

<https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid>

## Description

Given an `n x n` binary `grid`, in one step you can choose two **adjacent rows** of the grid and swap them.

A grid is said to be **valid** if all the cells above the main diagonal are **zeros**.

Return *the minimum number of steps* needed to make the grid valid, or **-1** if the grid cannot be valid.

The main diagonal of a grid is the diagonal that starts at cell `(1, 1)` and ends at cell `(n, n)`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/07/28/fw.jpg)

```
**Input:** grid = [[0,0,1],[1,1,0],[1,0,0]]
**Output:** 3
```

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/07/16/e2.jpg)

```
**Input:** grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]
**Output:** -1
**Explanation:** All rows are similar, swaps have no effect on the grid.
```

**Example 3:**

![](https://assets.leetcode.com/uploads/2020/07/16/e3.jpg)

```
**Input:** grid = [[1,0,0],[1,1,0],[1,1,1]]
**Output:** 0
```

**Constraints:**

* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 200`
* `grid[i][j]` is `0` or `1`

## ac

```java
```


---

# 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://jaywin.gitbook.io/leetcode/solutions/1536-minimum-swaps-to-arrange-a-binary-grid.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.
