# 01 matrix

difficulty**secondary**

Given a matrix of 0 and 1, find the distance from each element to the nearest 0.

The distance between two adjacent elements is 1.

Example 1:

Input:

0 0 0

0 1 0

1 1 1

Output:

0 0 0

0 1 0

1 2 1

### 1. To solve this problem, let’s start with a questionNumber of islands

The problem of island number is to find out the number of areas connected by 1 in a two-dimensional array

Input:

[

[‘1’,’1’,’0’,’0’,’0’],

[‘1’,’1’,’0’,’0’,’0’],

[‘0’,’0’,’1’,’0’,’0’],

[‘0’,’0’,’0’,’1’,’1’]

]

Output: 3

Explanation: each island can only be connected by adjacent land horizontally and / or vertically.

**The way to solve the problem of the number of islands can be through DFS, that is, depth first traversal. By setting the passed 1 into a special state, it shows that the area has already belonged to an island, until it can not be extended up and down, left and right**

```
class Solution {
public int numIslands(char[][] grid) {
if(grid==null||grid.length==0){
return 0;
}
int row = grid.length;
int col = grid[0].length;
int count=0;
//Number of islands
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j]=='1'){
count++;
infect(grid,i,j);
}
}
}
return count;
}
//Infection function
public void infect(char[][] ddx ,int i,int j){
if(i>=ddx.length||j>=ddx[0].length||i<0||j<0||ddx[i][j]!='1'){
return;
}
ddx[i][j]='2'; //Infect the passed 1 into 2, which means that the 1 already belongs to the current land
infect(ddx,i+1,j);
infect(ddx,i-1,j);
infect(ddx,i,j+1);
infect(ddx,i,j-1);
}
}
```

### 2. Another question about islandsThe largest area of the island

The maximum area of an island is similar to the number of islands, except that the maximum area of the island, i.e. the maximum value of a connected area, is needed

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0],

[0,0,0,0,0,0,0,1,1,1,0,0,0],

[0,1,1,0,1,0,0,0,0,0,0,0,0],

[0,1,0,0,1,1,0,0,1,0,1,0,0],

[0,1,0,0,1,1,0,0,1,1,1,0,0],

[0,0,0,0,0,0,0,0,0,0,1,0,0],

[0,0,0,0,0,0,0,1,1,1,0,0,0],

[0,0,0,0,0,0,0,1,1,0,0,0,0]]

For the given matrix above, 6 should be returned. Note that the answer should not be 11, because islands can only contain 1 in four directions, horizontal or vertical

**The solution is similar to the above, but each time you need to update the maximum island area!**

```
class Solution {
public int maxAreaOfIsland(int[][] grid) {
if(grid==null||grid.length==0||grid[0]==null||grid[0].length==0){
return 0;
}
int row = grid.length;
int col = grid[0].length;
int max =0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j]==1){
max = Math.max(max,infect(grid,i,j,row,col));
}
}
}
return max;
}
public int infect(int[][] grid,int i,int j,int row,int col){
if(i<0||i>=row||j<0||j>=col||grid[i][j]!=1){
return 0;
}
grid[i][j]=2;//Represents that the current 1 has been used!
int res = 1; //The initialization area is 1
//After depth first, four directions spread!
res+=infect(grid,i,j-1,row,col);
res+=infect(grid,i,j+1,row,col);
res+=infect(grid,i+1,j,row,col);
res+=infect(grid,i-1,j,row,col);
return res;
}
}
```

### 3. In fact, the 01 matrix problem is similar. You can also use the above DFS to start with each 1 and return when it encounters 0. However, the time complexity is very high and the submission time is timeout.

Several ideas are provided here

#### 1.DP

The following is my personal understanding: because when traversing 1 in the array, if it is a forward traversal, then there are two directions of information already known, namely the left direction and the up direction. The information of these two directions has been collected and can be used directly. Similarly, the reverse traversal is also the same, the down direction and the right direction are also collected, so you can use the positive and negative direction two times to correct and update the value of the specified position! It’s not easy to get all the information of the upper and lower elements by traversing the left side, so it’s not easy to get all the information from the left side and the lower side of the element!

```
class Solution {
public int[][] updateMatrix(int[][] matrix) {
int len = matrix.length;
int width = matrix[0].length;
for(int i = 0 ;i < len;i++){
for(int j = 0; j < width;j++){
if(matrix[i][j] == 1){
matrix[i][j] = 10000; //Assign a large value first
}
if(i > 0){ //At the first level, there is no information above
matrix[i][j] = Math.min( matrix[i][j],matrix[i -1][j] + 1); //Information on the location above
}
if(j > 0){ //In the first column, there is no information on the left
matrix[i][j] = Math.min(matrix[i][j],matrix[i][j - 1] + 1); //Information about the position on the left
}
}
}
//Same as above
for(int i = len - 1;i >= 0;i--){
for(int j = width - 1; j >= 0; j--){
if(i < len -1){
matrix[i][j] = Math.min( matrix[i][j],matrix[i + 1][j] + 1); //Information on the location below
}
if(j < width - 1){
matrix[i][j] = Math.min( matrix[i][j],matrix[i][j + 1] + 1); //Information on the right position
}
}
}
return matrix;
}
}
```

#### 2.BFS

Ideas:

From leetcode – Sweet aunt

We are familiar with “tree’s BFs” (a typical “single source BFS”):

First of all, the root node is queued, and then a layer of brainless traversal is OK.

The same is true of “BFs of graph” (BFs of multiple sources). The difference between BFs of tree and BFs of tree is as follows

A tree has only one root, while a graph can have multiple source points. Therefore, it is necessary to queue multiple source points first;

Tree is directed, so there is no need to identify whether it has been accessed, but for an undirected graph, it must be marked whether it has been accessed! And in order to prevent a node from joining the queue many times, it is necessary to set it as visited before joining the queue!

The specific processBFS+DP

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint