日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

搜索:深搜/广搜 获取岛屿数量

發布時間:2023/11/27 生活经验 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 搜索:深搜/广搜 获取岛屿数量 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目描述:
用一個二維數組代表一張地圖,這張地圖由字符“0”與字符“1”組 成,其中“0”字符代表水域,“1”字符代表小島土地,小島“1”被 水“0”所包圍,當小島土地“1”在水平和垂直方向相連接時,認 為是同一塊土地。求這張地圖中小島的數量

解決導圖如下:

代碼如下:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>using namespace std;void dfs(std::vector<std::vector<int> > &mark,std::vector<std::vector<char> > &map,int x,int y) {mark[x][y] = 1;int dx[] = {-1,1,0,0};int dy[] = {0,0,-1,1};for (int i = 0;i < 4; ++i) {int newx = x + dx[i];int newy = y + dy[i];if (newx < 0 || newx >= map.size() || newy < 0 || newy >= map[i].size() ) {continue;}if (mark[newx][newy] == 0 && map[newx][newy] == '1') {dfs(mark, map, newx, newy);}}
}void bfs(std::vector<std::vector<int> > &mark,std::vector<std::vector<char> > &map,int x,int y) {mark[x][y] = 1;queue<pair<int,int>> Q;int dx[] = {-1,1,0,0};int dy[] = {0,0,-1,1};Q.push(make_pair(x,y));while(!Q.empty()) {/* code */x = Q.front().first;y = Q.front().second;Q.pop();for (int i = 0;i < 4; ++i) {int newx = dx[i] + x;int newy = dy[i] + y;if(newx < 0 || newx >= map.size() || newy < 0 || newy >= map[i].size()) {continue;}if (mark[newx][newy] == 0 && map[newx][newy] == '1') {Q.push(make_pair(newx,newy));mark[newx][newy] = 1;}}}
}int get_island_nums(std::vector<std::vector<char> > &map) {int island_num = 0;std::vector<std::vector<int> > mark;for (int i = 0;i < map.size(); ++i) {mark.push_back(std::vector<int> ());for (int j = 0;j < map.size(); ++j) {mark[i].push_back(0);}}for (int i = 0; i < map.size(); ++i) {for (int j = 0;j < map[i].size(); ++j){if (mark[i][j] == 0 && map[i][j] == '1') {//dfs(mark, map, i ,j);bfs(mark, map, i ,j);island_num ++;}}}return island_num;
}int main(int argc, char const *argv[])
{char str[10][10] = {"11100", "11000", "00100", "00011"};std::vector<std::vector<char> > map;for (int i = 0; i < 4; ++i) {map.push_back(std::vector<char> ());for (int j = 0;j < 5; ++j) {map[i].push_back(str[i][j]);}}cout << get_island_nums(map) << endl; return 0;
}

總結

以上是生活随笔為你收集整理的搜索:深搜/广搜 获取岛屿数量的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。