LeetCod Brushing Notes

Table of contents

One. 2496. The maximum value of the string in the array

 Ideas:

code:

2. Interview question 16.19. The size of the water area

 Ideas:

 code:

 3. LCP 41. Reverse Chess

 Ideas:

code:

 1595. The Minimum Cost of Connecting Two Sets of Points

​edit

Ideas:

code:


 

 

One. 2496. The maximum value of the string in the array

 Ideas:

Traverse the strings in the input array to determine whether each character of the string is a number. If the string contains only numbers, convert the string to the number represented in decimal, otherwise the value is the length of the string. Finally returns the maximum value in the string array.

code:

class Solution {
public:
    int maximumValue(vector<string>& strs) {
        int cnt=0;
        for(auto& str:strs){
            bool flage=true;
            for(char& s:str){
                if(!isdigit(s)){
                    flage=false;
                    break;
                } 
            }
            cnt=max(cnt,flage?stoi(str):(int)str.size());
        }
        return cnt;
    }
};

Precautions:

isdigit() is a character that detects whether a character is a digit.

stoi() converts a string of numbers to a number.

The return value of string.size() is of unsigned type and needs to be converted.

 


 

2. Interview question 16.19. The size of the water area

 Ideas:

  1. Starting from 0 in the grid graph, DFS visits 0 in eight directions and marks these 0s as "visited". When the code is implemented, 0 can be directly changed to 1.
  2. In the DFS process, the number of grids visited in each direction is counted, and the number is accumulated to obtain the pond size cnt.
  3. Every time starting from a new 0 (starting point), it means that a new pond has been found, and the pond size obtained by DFS is added to the answer.
  4. Use the sort function to sort the answers and return them.

 code:

class Solution {
public:
    int fang[8][2]={
   
   {1,0},{0,1},{-1,0},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};
   int dfs(vector<vector<int>> &land, int x, int y) {
        if (x < 0 || x >= land.size() || y < 0 || y >= land[x].size() || land[x][y])
            return 0;
        land[x][y] = 1; 
        // 标记 (x,y) 被访问,避免重复访问
        int cnt = 1;
        // 访问八方向的
        for(int i=0;i<8;i++)
            cnt+= dfs(land,x+fang[i][0],y+fang[i][1]);
        return cnt;
    }
    vector<int> pondSizes(vector<vector<int>>& land) {
        int hang=land.size();
        int lie=land[0].size();
        vector<int> s;
        for(int i=0;i<hang;i++){
            for(int j=0;j<lie;j++){
                if(land[i][j]==0){
                    int p=dfs(land,i,j);
                    s.push_back(p);
                }
            }
        }
        sort(s.begin(),s.end());
        return s;
    }
};

 


 

 3. LCP 41. Reverse Chess

 Ideas:

We noticed that the maximum size of the chessboard in the title is 8×8, so we can try to enumerate all the vacant positions as the next position to place the black chess, and then use the breadth-first search method to calculate the position that can be flipped under this position The number of white pieces, just find the maximum value. We define a function bfs(i,j), which represents the number of white pieces that can be flipped after placing a black piece at (i,j) position on the board. In the function, we use the queue for breadth-first search, put (i,j) into the queue at the beginning, and then take out the position of the head of the team continuously, and traverse the eight directions of the board. If there is a continuous white chess in this direction , and there is a black piece at the end, then all the white pieces before the black piece can be flipped, put the positions of these white pieces into the queue, and continue the breadth-first search. Finally, we return the number of white pieces that can be flipped.

code:

class Solution {
public:
    const int dirs[8][2] = {
        {1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}
    };

    bool judge(const vector<string>& chessboard, int x, int y, int dx, int dy) {
        x += dx;
        y += dy;
        while (0 <= x && x < chessboard.size() && 0 <= y && y < chessboard[0].size()) {
            if (chessboard[x][y] == 'X') {
                return true;
            } else if (chessboard[x][y] == '.') {
                return false;
            }
            x += dx;
            y += dy;
        }
        return false;
    }

    int bfs(vector<string> chessboard, int px, int py) {
        int cnt = 0;
        queue<pair<int, int>> q;
        q.emplace(px, py);
        chessboard[px][py] = 'X';
        while (!q.empty()) {
            pair<int, int> t = q.front();
            q.pop();
            for (int i = 0; i < 8; ++i) {
                if (judge(chessboard, t.first, t.second, dirs[i][0], dirs[i][1])) {
                    int x = t.first + dirs[i][0], y = t.second + dirs[i][1];
                    while (chessboard[x][y] != 'X') {
                        q.emplace(x, y);
                        chessboard[x][y] = 'X';
                        x += dirs[i][0];
                        y += dirs[i][1];
                        ++cnt;
                    }
                }
            }
        }
        return cnt;
    }

    int flipChess(vector<string>& chessboard) {
        int res = 0;
        for (int i = 0; i < chessboard.size(); ++i) {
            for (int j = 0; j < chessboard[0].size(); ++j) {
                if (chessboard[i][j] == '.') {
                    res = max(res, bfs(chessboard, i, j));
                }
            }
        }
        return res;
    }
};

 


 

 1595. The Minimum Cost of Connecting Two Sets of Points

Ideas:


        Enumerate the first group of items. For these n items, each item has 2^m connection states (one item can be connected to multiple items of another group), and there are 2^m connection methods. Enumerate n items. For each state set of the i-th item, calculate the minimum cost of the total state set of him and the first i-1 items. Here, if it is a violent direct enumeration, the time complexity is O(n2^ m2^m)
Because there are a total of n items, the size of the first i-1 item state set is 2^m, and the size of the current i-th item state set is 2^m. The state set of the current
item i is the previous i item state set There are two cases when subsetting:
1: When the state set of item i has no intersection with the state set of the previous i-1 items, the combination of the two sets may make the cost of the union smaller 2: The state set of
item i and the previous i-1 items When the state set of 1 item has an intersection, item i can only update the state when it connects a line to the second group. For the binary state of the first i item, it is definitely a waste to connect the current item, but only part of the case 1 that has no intersection has been included, so in order to prevent the current i-th item from being disconnected, enumerate again Connect only one line at a time to prevent the current item from falling

code:

class Solution {
public:
    int connectTwoGroups(vector<vector<int>> &cost) {
        int m = cost[0].size(), f[1 << m];
        f[0] = 0;
        for (int j = 0; j < m; j++) {
            int mn = INT_MAX;
            for (auto &c: cost)
                mn = min(mn, c[j]);
            int bit = 1 << j;
            for (int mask = 0; mask < bit; mask++)
                f[bit | mask] = f[mask] + mn;
        }
        for (auto &row: cost) {
            for (int j = (1 << m) - 1; j >= 0; j--) {
                int res = INT_MAX;
                for (int k = 0; k < m; k++) 
                    res = min(res, f[j & ~(1 << k)] + row[k]);
                f[j] = res;
            }
        }
        return f[(1 << m) - 1];
    }
};

Guess you like

Origin blog.csdn.net/m0_73731708/article/details/131352236