标签:
图的转化,想了N久没想出来,看了题解发现自己其实想的差不多了,但是想多了(ORZ流泪)
把图扩大两倍(就是一个斜杠占2个位置)
走8个发现,走斜对角的时候需要特判
写完一次就AC了
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 80; const int maxd = 222; const int dir[8][2] = {{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}}; int n,m; int nn,mm; char smat[maxn][maxn]; int mat[maxd][maxd]; int vis[maxd][maxd]; int aim_x,aim_y; int ans_num; int ans_len; void debug(){ for(int i = 0; i < nn; i++){ for(int j = 0; j < mm; j++){ printf("%d ",mat[i][j]); } puts(""); } } bool judge(int x,int y,int d){ if(d < 4) return true; else if(d == 4){ //1 1 if(mat[x + 1][y] == 2 && mat[x][y + 1] == 2) return false; else return true; } else if(d == 5){//1 -1 if(mat[x + 1][y] == 1 && mat[x][y - 1] == 1) return false; else return true; } else if(d == 6){//-1 1 if(mat[x - 1][y] == 1 && mat[x][y + 1] == 1) return false; else return true; } else if(d == 7){ // -1 -1 if(mat[x - 1][y] == 2 && mat[x][y - 1] == 2) return false; else return true; } } void dfs(int x,int y,int px,int py,int step){ vis[x][y] = 1; for(int d = 0; d < 8; d++){ int xx = x + dir[d][0]; int yy = y + dir[d][1]; if(xx >= 0 && xx < nn && yy >= 0 && yy < mm){ if(!vis[xx][yy] && !mat[xx][yy] && judge(x,y,d)){ dfs(xx,yy,x,y,step + 1); return; } else{ if((xx != px || yy != py) && (xx == aim_x && yy == aim_y)){ ans_num ++; ans_len = max(ans_len,step); return; } } } } return; } int main(){ int Case = 1; while(scanf("%d%d",&m,&n)){ if(!n && !m) break; nn = n * 2; mm = m * 2; ans_num = 0; ans_len = -1; memset(mat,0,sizeof(mat)); memset(vis,0,sizeof(vis)); for(int i = 0; i < n; i++) scanf("%s",smat[i]); for(int i = 0,ii = 0; ii < n; i += 2,ii ++){ for(int j = 0,jj = 0; jj < m; j += 2,jj ++){ if(smat[ii][jj] == '\\'){ mat[i][j] = 1; mat[i + 1][j + 1] = 1; } else if(smat[ii][jj] == '/'){ mat[i + 1][j] = 2; mat[i][j + 1] = 2; } } } //debug(); for(int i = 0; i < nn; i++){ for(int j = 0; j < mm; j++){ if(!mat[i][j] && !vis[i][j]){ aim_x = i; aim_y = j; dfs(i,j,-1,-1,0); } } } printf("Maze #%d:\n",Case++); if(!ans_num) printf("There are no cycles.\n"); else printf("%d Cycles; the longest has length %d.\n",ans_num,ans_len + 1); puts(""); } return 0; }
标签:
原文地址:http://blog.csdn.net/u013451221/article/details/44517295