1267. 통신에 참여한 서버를 집계한다(연통 블록 깊이 찾기)

통신 참여 서버 통계
class Solution {
public:
    int vis[260][260] = {0};
    // vector> res;
    int m,n,ans=0;
    int countServers(vector<vector<int>>& grid) {
        m = grid.size();
        n = grid[0].size();
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(grid[i][j] && !vis[i][j]){
                    vector<int> list;
                    dfs(i,j,list,grid);
                    if(list.size()>1){
                        ans+=list.size();
                    }     
                }
            }
        }
        return ans;
    }
    void dfs(int x,int y,vector<int> &list,vector<vector<int>>& grid){
        vis[x][y] = 1;
        list.push_back(x*250+y);
        for(int i=0;i<m;i++){
            if(grid[i][y] && !vis[i][y]){
                dfs(i,y,list,grid);
            }
        }
        for(int j=0;j<n;j++){
            if(grid[x][j] && !vis[x][j]){
                dfs(x,j,list,grid);
            }
        }
    }
};

좋은 웹페이지 즐겨찾기