DFS鎴朆FS(娣卞害浼樺厛鎼滅储鎴栧箍搴︿紭鍏堟悳绱㈤亶鍘嗘棤鍚戝浘)-04-鏃犲悜鍥?宀涘笨鏁伴噺
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DFS鎴朆FS(娣卞害浼樺厛鎼滅储鎴栧箍搴︿紭鍏堟悳绱㈤亶鍘嗘棤鍚戝浘)-04-鏃犲悜鍥?宀涘笨鏁伴噺相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/push' title='push'>push mis first sig pre class pair 骞垮害 and
缁欏畾涓€涓敱 鈥?鈥橈紙闄嗗湴锛夊拰 鈥?鈥橈紙姘达級缁勬垚鐨勭殑浜岀淮缃戞牸锛岃绠楀矝灞跨殑鏁伴噺銆備竴涓矝琚按鍖呭洿锛屽苟涓斿畠鏄€氳繃姘村钩鏂瑰悜鎴栧瀭鐩存柟鍚戜笂鐩搁偦鐨勯檰鍦拌繛鎺ヨ€屾垚鐨勩€備綘鍙互鍋囪缃戞牸鐨勫洓涓竟鍧囪姘村寘鍥淬€?/p>
绀轰緥 1:
杈撳叆:
11110
11010
11000
00000
杈撳嚭: 1
绀轰緥 2:
杈撳叆:
11000
11000
00100
00011
杈撳嚭: 3
1 class Solution { 2 public: 3 int dist[4][2] = {0,1,0,-1,1,0,-1,0}; 4 queue<pair<int,int>>que; 5 void dfs(vector<vector<char>>& grid,vector<vector<int>>& sign,int i,int j,int row,int col,int num){ 6 sign[i][j] = 1; 7 int ii,jj; 8 for(int zz = 0;zz < 4;zz++){ 9 ii = i + dist[zz][0]; 10 jj = j + dist[zz][1]; 11 if(ii < 0||jj < 0||ii >= row||jj >= col) continue; 12 if(sign[ii][jj] == 1) continue; 13 if(grid[ii][jj] == 鈥?/span>1鈥?/span>) 14 dfs(grid,sign,ii,jj,row,col,num); 15 } 16 } 17 void bfs(vector<vector<char>>& grid,vector<vector<int>>& sign,int i,int j,int row,int col,int num){ 18 sign[i][j] = 1; 19 int ii,jj; 20 for(int zz = 0;zz < 4;zz++){ 21 ii = i + dist[zz][0]; 22 jj = j + dist[zz][1]; 23 if(ii < 0||jj < 0||ii >= row||jj >= col) continue; 24 if(sign[ii][jj] == 1) continue; 25 if(grid[ii][jj] == 鈥?/span>1鈥?/span>){ 26 sign[ii][jj] = 1; 27 que.push({ii,jj}); 28 } 29 } 30 while(!que.empty()){ 31 ii = que.front().first; 32 jj = que.front().second; 33 que.pop(); 34 bfs(grid,sign,ii,jj,row,col,num); 35 } 36 37 } 38 int numIslands(vector<vector<char>>& grid) { 39 if(grid.size() == 0||grid[0].size() == 0) 40 return 0; 41 int row = grid.size(); 42 int col = grid[0].size(); 43 int num = 0; 44 vector<vector<int>>sign(row,vector<int>(col,0)); 45 for(int i = 0 ;i < row;i++){ 46 for(int j = 0;j < col;j++){ 47 if(sign[i][j] == 0 && grid[i][j] == 鈥?/span>1鈥?/span>){ 48 num++; 49 dfs(grid,sign,i,j,row,col,num); 50 } 51 } 52 } 53 return num; 54 } 55 };
以上是关于DFS鎴朆FS(娣卞害浼樺厛鎼滅储鎴栧箍搴︿紭鍏堟悳绱㈤亶鍘嗘棤鍚戝浘)-04-鏃犲悜鍥?宀涘笨鏁伴噺的主要内容,如果未能解决你的问题,请参考以下文章