LC 959. Regions Cut By Slashes

In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of /\, or blank space.  These characters divide the square into contiguous regions.

(Note that backslash characters are escaped, so a \ is represented as "\\".)

Return the number of regions.

我的DFS解法。

Runtime: 32 ms, faster than 12.39% of C++ online submissions for Regions Cut By Slashes.

#include <string>
#include <iostream>
#include <vector>
using namespace std;
int dirs[8][2] = {{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};
class Solution {
public:
  int regionsBySlashes(vector<string>& grid) {
    size_t n = grid.size();
    vector<vector<int>> mtx(4*n, vector<int>(4*n, 0));
    for(int i=0; i<n; i++){
      for(int j=0; j<n; j++){
        if(grid[i][j] == '/'){
          mtx[4*i][4*j+3] = 1;
          mtx[4*i+1][4*j+2] = 1;
          mtx[4*i+2][4*j+1] = 1;
          mtx[4*i+3][4*j] = 1;
        }else if(grid[i][j] == '\\'){
          mtx[4*i][4*j] = 1;
          mtx[4*i+1][4*j+1] = 1;
          mtx[4*i+2][4*j+2] = 1;
          mtx[4*i+3][4*j+3] = 1;
        }
      }
    }
    int ret = 0;
    for(int i=0; i<4*n; i++){
      for(int j=0; j<4*n; j++){
        if(mtx[i][j] == 0) ret++;
        dfs(mtx, i, j);
      }
    }
    return ret;
  }
  void dfs(vector<vector<int>>& mtx, int x, int y){
    size_t n = mtx.size();
    if(x < 0 || x >= n || y < 0 || y >= n || mtx[x][y] != 0) return ;
    mtx[x][y] = -1;
    for(int i=0; i<4; i++){
      int newx = x+dirs[i][0];
      int newy = y+dirs[i][1];
      if(newx >= 0 && newy >= 0 && newx < n && newy < n && i >= 4){
        if(mtx[newx][y] == 1 && mtx[x][newy] == 1) continue;
      }
      dfs(mtx, newx, newy);
    }
  }
};

网上的unionfound解法。

class Solution {
public:
   int count, n;
   vector<int> f;
   int regionsBySlashes(vector<string>& grid) {
        n = grid.size();
        count = n * n * 4;
        for (int i = 0; i < n * n * 4; ++i)
            f.push_back(i);
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                if (i > 0) uni(g(i - 1, j, 2), g(i, j, 0));
                if (j > 0) uni(g(i , j - 1, 1), g(i , j, 3));
                if (grid[i][j] != '/') {
                    uni(g(i , j, 0), g(i , j,  1));
                    uni(g(i , j, 2), g(i , j,  3));
                }
                if (grid[i][j] != '\\') {
                    uni(g(i , j, 0), g(i , j,  3));
                    uni(g(i , j, 2), g(i , j,  1));
                }
            }
        }
        return count;
    }

    int find(int x) {
        if (x != f[x]) {
            f[x] = find(f[x]);
        }
        return f[x];
    }
    void uni(int x, int y) {
        x = find(x); y = find(y);
        if (x != y) {
            f[x] = y;
            count--;
        }
    }
    int g(int i, int j, int k) {
        return (i * n + j) * 4 + k;
    }
};

猜你喜欢

转载自www.cnblogs.com/ethanhong/p/10193441.html
cut