图元识别
//给图元编号 #include <iostream> #include <queue> using namespace std; int pathLength = 0; struct position { int col; int row; }; int labelComponent(int** grid, int row, int col) //row 与col已经经过扩展,形成边界 { position offset[4]; offset[0].row = 0; offset[0].col = 1; offset[1].row = 1; offset[1].col = 0; offset[2].row = 0; offset[2].col = -1; offset[3].row = -1; offset[3].col = 0; for (int i = 0; i < col; i++) grid[0][i] = grid[row - 1][i] = 1; for (int i = 0; i < row; i++) grid[i][0] = grid[i][col - 1] = 1; int numOfNbrs = 4; queue<position> q; position nbr, here; int id = 1; for (int i = 1; i < row - 1; i++) for (int j = 1; j < col - 1; j++) { if (grid[i][j] == 0) { here.row = i; here.col = j; grid[here.row][here.col] = ++id; while (true) { for (int k = 0; k < numOfNbrs; k++) { nbr.row = here.row + offset[k].row; nbr.col = here.col + offset[k].col; if (grid[nbr.row][nbr.col] == 0) { grid[nbr.row][nbr.col] = id; q.push(nbr); } } if (q.empty()) break; here = q.front(); q.pop(); } } } return id - 1; } int main() { int row, col; cin >> row >> col; row += 2; col += 2; int** grid = new int*[row]; //delete[] for (int i = 0; i < row; i++) grid[i] = new int[col]; //delete[] for (int i = 1; i < row - 1; i++) for (int j = 1; j < col - 1; j++) cin >> grid[i][j]; cout << labelComponent(grid, row, col); for (int i = 0; i < row; i++) delete[] grid[i]; delete[] grid; }
posted on 2020-09-10 15:54 waterrzhang 阅读(125) 评论(0) 编辑 收藏 举报