방향성을 가지는 그래프를 탐색하는 것으로 dfs, bfs 모두 가능하다.
이 문제는 dfs로 풀어봤다.
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
| #include <iostream> #include <cstring> using namespace std; int n, arr[102][102], v[102][102], ans[102][102], cs; void dfs(int s) { for(int i = 1; i <= n; i++) { if(!arr[s][i] || v[s][i]) continue; v[s][i] = 1; ans[cs][i] = 1; dfs(i); } } int main() { cin >> n; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) cin >> arr[i][j]; for(int i = 1; i <= n; i++) { memset(v, 0, sizeof(v)); cs = i; dfs(i); } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) cout << ans[i][j] << " "; cout << endl; } }
|