iT邦幫忙

2023 iThome 鐵人賽

DAY 16
0
自我挑戰組

leetcode題目分享系列 第 16

[Day 16] 1631. Path With Minimum Effort

  • 分享至 

  • xImage
  •  

這題運用dfs & Binary Search,dfs用來跑格子,BS逐漸調整下限至upper < lower

class Solution {
private:
    bool visited[105][105];  // Visited cells tracker
    int directions_x[4] = {0, 1, -1, 0};  // Changes in x coordinate for four directions
    int directions_y[4] = {1, 0, 0, -1};  // Changes in y coordinate for four directions
    int numRows, numCols;  // Number of rows and columns in the matrix

public:

    // Depth-First Search to explore the path with a given limit effort
    void dfs(int x, int y, int limitEffort, vector<vector<int>>& heights){
        if (visited[x][y])
            return;
        visited[x][y] = true;

        // Stop if we've reached the bottom-right cell
        if (x == numRows - 1 && y == numCols - 1)
            return ;

        // Explore each direction (up, down, left, right)
        for (int i = 0; i < 4; i++) {
            int new_x = x + directions_x[i];
            int new_y = y + directions_y[i];

            // Check if the new coordinates are within bounds
            if (new_x < 0 || new_x >= numRows || new_y < 0 || new_y >= numCols)
                continue;
            
            // Go to next cell if the effort is within limit
            int newEffort = abs(heights[x][y] - heights[new_x][new_y]);
            if (newEffort <= limitEffort)
                dfs(new_x, new_y, limitEffort, heights);
        }
    }

    int minimumEffortPath(vector<vector<int>>& heights) {
        numRows = heights.size(); 
        numCols = heights[0].size();

        // Bound for our binary search
        int lowerLimit = 0, upperLimit = 1e6;

        while (lowerLimit < upperLimit) {
            int mid = (upperLimit + lowerLimit) / 2;
            memset(visited, 0, sizeof visited);
            dfs(0, 0, mid, heights);

            if (visited[numRows - 1][numCols - 1])
                upperLimit = mid; 
            else
                lowerLimit = mid + 1;
        }

        return lowerLimit;
    }
};

上一篇
[Day 15] 1584. Min Cost to Connect All Points
下一篇
[Day 17] 847. Shortest Path Visiting All Nodes
系列文
leetcode題目分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言