zoukankan      html  css  js  c++  java
  • [LeetCode]130 Surrounded Regions(DFS)

    题目链接:https://leetcode.com/problems/surrounded-regions/?tab=Description

    题意:把非边界的O改成X。

    先dfs边界的,打好标记。把没变的变成X后同时更新标记的为O。

     1 class Solution {
     2 public:
     3     const int dx[5] = {0, 0, 1, -1};
     4     const int dy[5] = {1, -1, 0, 0};
     5     int n, m;
     6     bool ok(int x, int y) {
     7         return x >= 0 && x < n && y >= 0 && y < m;
     8     }
     9     void dfs(vector<vector<char>>& board, int x, int y) {
    10         board[x][y] = 'Q';
    11         for(int i = 0; i < 4; i++) {
    12             int xx = x + dx[i];
    13             int yy = y + dy[i];
    14             if(ok(xx, yy) && board[xx][yy] == 'O') {
    15                 dfs(board, xx, yy);
    16             }
    17         }
    18     }
    19     void solve(vector<vector<char>>& board) {
    20         n = board.size();
    21         if(n == 0) return;
    22         m = board[0].size();
    23         for(int i = 0; i < n; i++) {
    24             if(board[i][0] == 'O') dfs(board, i, 0);
    25             if(board[i][m-1] == 'O') dfs(board, i, m-1);
    26         }
    27         for(int i = 0; i < m; i++) {
    28             if(board[0][i] == 'O') dfs(board, 0, i);
    29             if(board[n-1][i] == 'O') dfs(board, n-1, i);            
    30         }
    31         for(int i = 0; i < n; i++) {
    32             for(int j = 0; j < m; j++) {
    33                 if(board[i][j] == 'O') board[i][j] = 'X';
    34                 else if(board[i][j] == 'Q') board[i][j] = 'O';
    35             }
    36         }
    37     }
    38 };
  • 相关阅读:
    python---django初步了解以及安装(包括Django网页首次无法访问的原因及解决方法,以及在linux服务器上布置无法启动的原因)
    pytho部分命令
    三层架构
    CardView
    SimpleTagImageView
    MultiCardMenu
    DashClock
    SuperToolTips
    MPAndroidChart
    SlideLayout
  • 原文地址:https://www.cnblogs.com/kirai/p/6533706.html
Copyright © 2011-2022 走看看