---
# System prepended metadata

title: 1162. As Far from Land as Possible
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}    
/* 設定連結 */
a,
.open-files-container li.selected a {
    color: #89FFF8;
    
}
a:hover,
.open-files-container li.selected a:hover {
    color: #89FFF890;
}
   
</style>

###### tags: `Leetcode`

# 1162. As Far from Land as Possible

###### Link : https://leetcode.com/problems/as-far-from-land-as-possible/description/

## 題目

grid中1為陸地；0為水
找到離陸地最遠的水的距離

## 程式碼I
```cpp=
class Solution {
public:
    int maxDistance(vector<vector<int>>& grid) {//using BFS
        const int n = grid.size();
        queue<pair<int, int>> q;
        bool allOne = true;
        for(int i = 0;i < n;++i){//將所有的1放入queue
            for(int j = 0;j < n;++j){
                if(grid[i][j])
                    q.push({i, j});
                else allOne = false;
            }
        }
        if(allOne) return -1;//全都是1回傳-1
        int step = 2;
        while(!q.empty()){//BFS
            int size = q.size();
            for(int i = 0;i < size;++i){
                pair<int, int> loc = q.front(); q.pop();
                //遇到是0的(還沒走過) 放入queue並更新值
                if(loc.first + 1 < n && !grid[loc.first + 1][loc.second]){
                    grid[loc.first + 1][loc.second] = step;
                    q.push({loc.first + 1, loc.second});
                }
                if(loc.first - 1 >= 0 && !grid[loc.first - 1][loc.second]){
                    grid[loc.first - 1][loc.second] = step;
                    q.push({loc.first - 1, loc.second});
                }
                if(loc.second + 1 < n && !grid[loc.first][loc.second + 1]){
                    grid[loc.first][loc.second + 1] = step;
                    q.push({loc.first, loc.second + 1});
                }
                if(loc.second - 1 >= 0 && !grid[loc.first][loc.second - 1]){
                    grid[loc.first][loc.second - 1] = step;
                    q.push({loc.first, loc.second - 1});
                }
            }
            ++step;
        }
        //如全是0會回傳2 - 3 = -1 符合題目要求
        return step - 3;
    }
};
```

## Date 
### 2023/2/10