源博客
//观察可看出几张图中圈数不一样,可以根据此来识别每张图 //先dfs整张图,填充颜色编号-----》将像素点为1的点的编号m存储起来-----》将环数存储进以m为下标的set中 #include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <set> #include <algorithm> using namespace std; const int maxn = 200 + 10; char bin[256][5], line[maxn]; int H, W, pic[maxn][maxn], color[maxn][maxn]; vector<set<int> > neighbor; const int dir_row[] = {-1, 1, 0, 0}; const int dir_col[] = {0, 0, -1, 1}; void dfs(int row, int col, int num) { color[row][col] = num; for(int i = 0; i < 4; i++) { int row2 = row + dir_row[i]; int col2 = col + dir_col[i]; if(row2 >= 0 && row2 < H && col2 >= 0 && col2 < W && pic[row2][col2] == pic[row][col] && color[row2][col2] == 0) dfs(row2, col2, num); } } void decode(char c, int row, int col) { for(int i = 0; i < 4; i++) pic[row][col+i] = bin[c][i] - '0'; } void check_neighbor(int r, int c) { for(int i = 0; i < 4; i++) { int r2 = r + dir_row[i]; int c2 = c + dir_row[i]; if(r2 >= 0 && r2 < H && c2 >= 0 && c2 < W && pic[r2][c2] == 0 && color[r2][c2] != 1) //圈外的0的color是1 neighbor[color[r][c]].insert(color[r2][c2]); } } const char *s = "WAKJSD"; char recognize(int num) { int c = neighbor[num].size(); return s[c]; } int main() { strcpy(bin['0'], "0000"); strcpy(bin['1'], "0001"); strcpy(bin['2'], "0010"); strcpy(bin['3'], "0011"); strcpy(bin['4'], "0100"); strcpy(bin['5'], "0101"); strcpy(bin['6'], "0110"); strcpy(bin['7'], "0111"); strcpy(bin['8'], "1000"); strcpy(bin['9'], "1001"); strcpy(bin['a'], "1010"); strcpy(bin['b'], "1011"); strcpy(bin['c'], "1100"); strcpy(bin['d'], "1101"); strcpy(bin['e'], "1110"); strcpy(bin['f'], "1111"); int kase = 0; while(scanf("%d%d", &H, &W) == 2 && H && W) { memset(pic, 0, sizeof(pic)); memset(color, 0, sizeof(color)); for(int i = 0; i < H; i++) { scanf("%s", line); for(int j = 0; j < W ;j++) decode(line[j], i + 1, j * 4 + 1); //将输入的数据解码到pic[i+1][j*4+1],注意行列是从下标1开始 } H += 5; //按理说加一就行,为什么 H += 1 会WA? 换成 H += 2 刚好可以AC ??????????????????? W = W * 4 + 5; //因为原来的输入是16进制,转化为10进制后每个原来的16进制代表4个数字 int cnt = 0; vector<int> vec; for(int i = 0; i < H; i++) for(int j = 0; j < W; j++) { if(!color[i][j]) { dfs(i, j, ++cnt); if(pic[i][j] == 1) vec.push_back(cnt); //把图像中等于1的像素点的color编号都存储进vec容器 } } neighbor.clear(); //neighbor用来存储环内的点 neighbor.resize(cnt + 5); //其实相当于对每个成员初始化,去掉会引起RE,关于resize很容易用错,最好查下API文档 for(int i = 0; i < H; i++) for(int j = 0; j < W; j++) if(pic[i][j] == 1) check_neighbor(i, j); //将像素点为1周围的空环编号存储进neighbor容器里面 vector<char> ans; //存储结果 for(int i = 0; i < vec.size(); i++) ans.push_back(recognize(vec[i])); sort(ans.begin(), ans.end());//对结果进行整理排序 printf("Case %d: ", ++kase); for(int j = 0; j < ans.size(); j++) printf("%c", ans[j]); printf("\n"); } return 0; }
dfs找环
猜你喜欢
转载自blog.csdn.net/qq_43868883/article/details/100926973
今日推荐
周排行