dfs로 돌려가며 모든 좌표를 방문하면 된다.
단, 방문 조건은 해당 알파벳을 아직 지나가지 않았어야 하고 그 좌표도 방문하지 않았어야함.
그리고 방문 끝나면 다시 돌아와서 true 처리 해줬던거 false로 바꿔주기
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 | #include<cstdio> char arr[20][20]; bool visited[20][20]; bool check[28]; int r,c,temp=1,ans; int dx[]={0,0,1,-1}, dy[]={1,-1,0,0}; void dfs(int x, int y){ visited[x][y]=true; check[arr[x][y]-'A']=true; for(int k=0; k<4; k++){ int nx=x+dx[k]; int ny=y+dy[k]; if(0<=nx && nx<r && 0<=ny && ny<c){ char next=arr[nx][ny]; if(check[next-'A'] || visited[nx][ny]) continue; temp++; dfs(nx,ny); temp--; visited[nx][ny]=false; check[next-'A']=false; } } ans=temp>ans?temp:ans; } int main(void){ scanf("%d %d\n", &r, &c); for(int i=0; i<r; i++){ for(int j=0; j<c; j++) scanf("%c", &arr[i][j]); char temp; scanf("%c", &temp); } dfs(0,0); printf("%d", ans); return 0; } | cs |
'백준 2 > 백트래킹' 카테고리의 다른 글
| [백준 1759] 암호 만들기 (C++/Python) (0) | 2020.12.07 |
|---|---|
| [백준 6603] 로또 (C++/Python) (0) | 2020.12.07 |
| [백준 9663] N-Queen (0) | 2020.12.07 |
| [백준 15657] N과 M(8) (C++/Python) (0) | 2020.12.07 |
| [백준 15656] N과 M(7) (C++/Python) (0) | 2020.12.07 |