信息学奥赛一本通 1216:红与黑 / OpenJudge NOI 2.5 1818
生活随笔
收集整理的這篇文章主要介紹了
信息学奥赛一本通 1216:红与黑 / OpenJudge NOI 2.5 1818
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目鏈接】
ybt 1216:紅與黑
OpenJudge NOI 2.5 1818:紅與黑
【題目考點】
1. 連通塊問題
2. 深搜/廣搜
【解題思路】
1. 深搜
從第一個格子出發,遍歷所有可以前進的方向,前進到下一個格后,再遍歷可以前進的方向,走過的格子做標記,標記過的格子就不走了,不是黑色的格子不走。如果沒有可以走的格子,那么退回到上一位置,看其它前進方向的格子可不可以走。
每走一個格子,格子計數加1,如果退回,也不減少格子計數。深搜結束后,輸出格子計數。
2. 廣搜
將起始位置做標記,而后入隊。每出隊一個位置,看看能從這個位置走到哪些位置,可以走到的位置必須滿足3個條件:在地圖內,沒標記過,是黑色格子。將能從該位置走到的位置做標記,而后入隊。繼續出隊一個位置,循環此過程,直到隊空。
每標記一個位置,格子計數加1。廣搜結束后,輸出格子計數。
【注意】:該題中,w表示寬度,也就是列數。h表示高度,也就是行數。這是一個h行w列的矩陣。
【題解代碼】
解法1:深搜
#include <bits/stdc++.h> using namespace std; #define N 25 char mp[N][N];//地圖 int w, h, ans;//h:行數,w:列數,ans:結果計數 int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//方向數組 bool vis[N][N]; void dfs(int sx, int sy) {for(int i = 0; i < 4; ++i){int x = sx + dir[i][0], y = sy + dir[i][1];if(x >= 1 && x <= h && y >= 1 && y <= w && vis[x][y] == false && mp[x][y] != '#'){ans++;vis[x][y] = true;dfs(x, y);}} } int main() {int stx, sty;//起始位置while(true){cin >> w >> h;if(w == 0 && h == 0)return 0;for(int i = 1; i <= h; ++i)for(int j = 1; j <= w; ++j){cin >> mp[i][j];if(mp[i][j] == '@')stx = i, sty = j;}memset(vis, 0, sizeof(vis));//多組數據,注意狀態還原ans = 1;vis[stx][sty] = true;dfs(stx, sty);cout << ans << endl;}return 0; }解法2:廣搜
#include <bits/stdc++.h> using namespace std; #define N 25 struct Node {int x, y;Node(){}Node(int a, int b):x(a),y(b){} }; char mp[N][N];//地圖 int w, h;//w:列數 h:行數 int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//方向數組 bool vis[N][N]; int bfs(int sx, int sy)//傳入起始位置 {queue<Node> que;vis[sx][sy] = true;que.push(Node(sx, sy));int ct = 1;//計數,看可以到達幾個黑色格子while(que.empty() == false){Node u = que.front();que.pop();for(int i = 0; i < 4; ++i){int x = u.x + dir[i][0], y = u.y + dir[i][1];if(x >= 1 && x <= h && y >= 1 && y <= w && vis[x][y] == false && mp[x][y] != '#'){vis[x][y] = true;que.push(Node(x, y));ct++;}}}return ct; } int main() {int stx, sty;while(true){cin >> w >> h;if(w == 0 && h == 0)return 0;for(int i = 1; i <= h; ++i)for(int j = 1; j <= w; ++j){cin >> mp[i][j];if(mp[i][j] == '@')stx = i, sty = j;}memset(vis, 0, sizeof(vis));cout << bfs(stx, sty) << endl;}return 0; }總結
以上是生活随笔為你收集整理的信息学奥赛一本通 1216:红与黑 / OpenJudge NOI 2.5 1818的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信息学奥赛一本通 1009:带余除法 |
- 下一篇: 信息学奥赛一本通 1924:【03NOI