【leetcode】被围绕的区域
/*深度优先*/ void dfs(char** board,int r,int c,int row,int col) { if (r<0 || r>row-1 || c<0 || c>col-1 || board[r][c] != 'O') return; board[r][c] = 'A'; dfs(board,r+1,c,row,col); dfs(board,r-1,c,row,col); dfs(board,r,c+1,row,col); dfs(board,r,c-1,row,col); } void solve(char** board, int boardSize, int* boardColSize){ int row=boardSize,col=*boardColSize,i,j; if(!row) return; for (i=0; i<row; i++) { dfs(board,i,0,row,col); dfs(board,i,col-1,row,col); } for (i=1; i<col-1; i++) { dfs(board,0,i,row,col); dfs(board,row-1,i,row,col); } for (i=0; i<row; i++) { for (j=0; j<col; j++) { if (board[i][j] == 'A') board[i][j] = 'O'; else if (board[i][j] == 'O') board[i][j] = 'X'; } } }
/*广度优先*/ const int dx[4] = {1, -1, 0, 0}; const int dy[4] = {0, 0, 1, -1}; void solve(char** board, int boardSize, int* boardColSize) { int n = boardSize; if (n == 0) { return; } int m = boardColSize[0]; int** que = (int**)malloc(sizeof(int*) * n * m); for (int i = 0; i < n * m; i++) { que[i] = (int*)malloc(sizeof(int) * 2); } int l = 0, r = 0; for (int i = 0; i < n; i++) { if (board[i][0] == 'O') { board[i][0] = 'A'; que[r][0] = i, que[r++][1] = 0; } if (board[i][m - 1] == 'O') { board[i][m - 1] = 'A'; que[r][0] = i, que[r++][1] = m - 1; } } for (int i = 1; i < m - 1; i++) { if (board[0][i] == 'O') { board[0][i] = 'A'; que[r][0] = 0, que[r++][1] = i; } if (board[n - 1][i] == 'O') { board[n - 1][i] = 'A'; que[r][0] = n - 1, que[r++][1] = i; } } while (l < r) { int x = que[l][0], y = que[l][1]; l++; for (int i = 0; i < 4; i++) { int mx = x + dx[i], my = y + dy[i]; if (mx < 0 || my < 0 || mx >= n || my >= m || board[mx][my] != 'O') { continue; } board[mx][my] = 'A'; que[r][0] = mx, que[r++][1] = my; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (board[i][j] == 'A') { board[i][j] = 'O'; } else if (board[i][j] == 'O') { board[i][j] = 'X'; } } } for (int i = 0; i < n * m; i++) { free(que[i]); } free(que); }