首页 > 代码库 > [LeetCode]130 Surrounded Regions(DFS)
[LeetCode]130 Surrounded Regions(DFS)
题目链接:https://leetcode.com/problems/surrounded-regions/?tab=Description
题意:把非边界的O改成X。
先dfs边界的,打好标记。把没变的变成X后同时更新标记的为O。
1 class Solution { 2 public: 3 const int dx[5] = {0, 0, 1, -1}; 4 const int dy[5] = {1, -1, 0, 0}; 5 int n, m; 6 bool ok(int x, int y) { 7 return x >= 0 && x < n && y >= 0 && y < m; 8 } 9 void dfs(vector<vector<char>>& board, int x, int y) { 10 board[x][y] = ‘Q‘; 11 for(int i = 0; i < 4; i++) { 12 int xx = x + dx[i]; 13 int yy = y + dy[i]; 14 if(ok(xx, yy) && board[xx][yy] == ‘O‘) { 15 dfs(board, xx, yy); 16 } 17 } 18 } 19 void solve(vector<vector<char>>& board) { 20 n = board.size(); 21 if(n == 0) return; 22 m = board[0].size(); 23 for(int i = 0; i < n; i++) { 24 if(board[i][0] == ‘O‘) dfs(board, i, 0); 25 if(board[i][m-1] == ‘O‘) dfs(board, i, m-1); 26 } 27 for(int i = 0; i < m; i++) { 28 if(board[0][i] == ‘O‘) dfs(board, 0, i); 29 if(board[n-1][i] == ‘O‘) dfs(board, n-1, i); 30 } 31 for(int i = 0; i < n; i++) { 32 for(int j = 0; j < m; j++) { 33 if(board[i][j] == ‘O‘) board[i][j] = ‘X‘; 34 else if(board[i][j] == ‘Q‘) board[i][j] = ‘O‘; 35 } 36 } 37 } 38 };
[LeetCode]130 Surrounded Regions(DFS)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。