zoukankan      html  css  js  c++  java
  • 1162 地图分析

    https://leetcode-cn.com/problems/as-far-from-land-as-possible/submissions/

    动态规划 dp[i][j]表示前i,j的最小值

    int dpSearch(vector<vector<int>>& grid)
        {
            const int N = grid.size();
            const int INF = 200;
            int ans = -1;
            vector<vector<int>> dp(N, vector(N, INF));
            for(int r = 0; r < N; r++)
                for(int c = 0; c < N; c++)
                {
                    if(grid[r][c]) dp[r][c] = 0;
                    else dp[r][c] = min(r > 0 ? dp[r-1][c] : INF, c > 0 ? dp[r][c-1] : INF) + 1;
                }
            for(int r = N - 1; r >= 0; r--)
                for(int c = N - 1; c >= 0; c--)
                {
                    if(r + 1 < N) dp[r][c] = min(dp[r][c], dp[r+1][c] + 1);
                    if(c + 1 < N) dp[r][c] = min(dp[r][c], dp[r][c+1] + 1);
                } 
            for(int r = 0; r < N; r++)
                for(int c = 0; c < N; c++)
                    if(dp[r][c]) ans = max(ans, dp[r][c]);   
            return ans >= INF? -1 : ans;
        }
    

    BFS

    int maxDistance(vector<vector<int>>& grid) {
            int n = grid.size();
            int dxy[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
            queue<pair<int, int>> q;
            
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (grid[i][j] == 1) {
                        q.push(make_pair(i, j));
                    }
                }
            }
            if (q.empty() || q.size() == n * n) return -1;
    
            pair<int, int> cur;
            while (!q.empty()) {
                cur = q.front();
                q.pop();
                for (int i = 0; i < 4; i++) {
                    int raw = cur.first + dxy[i][0];
                    int column = cur.second + dxy[i][1];
                    if (raw >= 0 && raw < n && column >= 0 && column < n && grid[raw][column] == 0) {
                        grid[raw][column] = grid[cur.first][cur.second] + 1;
                        q.push(make_pair(raw, column));
                    }
                }
            }
            return grid[cur.first][cur.second] - 1;
        }
    
  • 相关阅读:
    Linux操作系统原理
    html标签简介(常用)
    Git常用命名
    Nuxt.js vue服务端渲染
    Sequelize 和 MySQL 对照Sequelize 和 MySQL 对照
    VScode 自定义用户代码块
    python对一个文本的解析
    API管理工具
    Flutter教程- Dart语言规范-知识点整理
    RESTful API
  • 原文地址:https://www.cnblogs.com/Hunter01/p/12595381.html
Copyright © 2011-2022 走看看