알고리즘
[DFS/그래프/하] 4963번 섬의 개수
심재철
2017. 10. 10. 04:14
기본 DFS문제 1인곳부터 dfs를 시작하되 방문한곳은 0으로 바꿔놓는다.
dfs를 시작하는곳에서 count를 증가시켜준다.
소스코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include <iostream> #include <algorithm> #include <vector> using namespace std; vector<int> result; bool input[51][51]; int n,m; int diffx[8] = {-1,0,1,-1,1,-1,0,1}; int diffy[8] = {1,1,1,0,0,-1,-1,-1}; void dfs(int x,int y) { if(x<1 || x>n || y<1 || y>m)return; if(input[x][y] == 0) return; input[x][y] = 0; for(int i=0; i<8; i++) { int nextX = x + diffx[i]; int nextY = y + diffy[i]; dfs(nextX,nextY); } return; } int main() { while(1) { cin>>m>>n; int count = 0; if(m==0&& n==0) break; for(int i=1; i<=n; i++) for(int j=1; j<=m; j++) cin>>input[i][j]; for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) { if(input[i][j]) { dfs(i,j); count++; } } } result.push_back(count); } for(int i=0; i<result.size(); i++) cout<<result[i]<<endl; return 0; } | cs |