本文共 2008 字,大约阅读时间需要 6 分钟。
解决方案:
要解决这个问题,我们需要找到矩阵中的所有被围绕的'O'区域,并将它们转换为'A',然后将未被围绕的'O'转换为'X'。我们可以使用广度优先搜索(BFS)来实现这一点。
这种方法确保了所有被围绕的'O'都会被正确标记,并在最后的转换过程中被正确处理。
import java.util.*;public class Solution130 { int[][] d = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; int m, n; public void solve(char[][] board) { m = board.length; if (m == 0) return; n = board[0].length; // 初始化队列 Deque queue = new LinkedList<>(); // 从边缘开始检查 for (int i = 0; i < n; i++) { if (board[0][i] == 'O') queue.add(new int[]{0, i}); if (board[m - 1][i] == 'O') queue.add(new int[]{m - 1, i}); } for (int i = 0; i < m; i++) { if (board[i][0] == 'O') queue.add(new int[]{i, 0}); if (board[i][n - 1] == 'O') queue.add(new int[]{i, n - 1}); } // BFS处理 while (!queue.isEmpty()) { int[] curr = queue.remove(); int x = curr[0], y = curr[1]; if (board[x][y] != 'O') continue; board[x][y] = 'A'; for (int i = 0; i < 4; i++) { int nx = x + d[i][0]; int ny = y + d[i][1]; if (nx >= 0 && nx < m && ny >= 0 && ny < n && board[nx][ny] == 'O') { queue.add(new int[]{nx, ny}); } } } // 最后转换状态 for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'A') { board[i][j] = 'O'; } else if (board[i][j] == 'O') { board[i][j] = 'X'; } } } }} d数组用于表示四个方向的移动,用于BFS遍历。这种方法确保了所有被围绕的'O'都会被正确处理,并且在转换过程中不会遗漏任何位置。
转载地址:http://ilhfk.baihongyu.com/