Monday, October 2, 2023

Leetcode 490. The Maze

 就是普通的dfs,区别就是选一个方向的时候可以直接走到走不动为止。

时间复杂度: O(n^2), n代表行数

空间复杂度: O(n^2), 用来存储visited二维数组,当然也可以通过改input实现


class Solution {
public:
    bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {
        int m = maze.size();
        int n = maze[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
       
        return dfs(maze, start[0], start[1], destination[0], destination[1], visited);
    }

private:
    bool dfs(vector<vector<int>>& maze, int i, int j, int di, int dj, vector<vector<bool>>& visited) {
        if (i == di && j == dj) {
            return true;
        }

        if (visited[i][j]) {
            return false;
        }
       
        visited[i][j] = true;
       
        vector<vector<int>> directions = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
       
        for (const auto& dir : directions) {
            int ni = i + dir[0];
            int nj = j + dir[1];
           
            while (ni >= 0 && ni < maze.size() && nj >= 0 && nj < maze[0].size() && maze[ni][nj] == 0) {
                ni += dir[0];
                nj += dir[1];
            }
           
            ni -= dir[0];
            nj -= dir[1];
           
            if (dfs(maze, ni, nj, di, dj, visited)) {
                return true;
            }
        }
       
        return false;
    }
};

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...