简化的围棋棋子规则(C++实现)
生活随笔
收集整理的這篇文章主要介紹了
简化的围棋棋子规则(C++实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
輸入棋盤:1 1 2 3 2 3
????????????????? 3 3 2 3 3 3
????????????????? 2 2 2 3 3 3
????????????????? 1 2 2 2 3 3
??????????????? ? 2 1 1 2 3 1???? (其中1代表空,2代表白子,3代表黑子)
輸出:白棋活子個數,黑棋活子個數
來源:華為校招實習生筆試題第二題
?????????????????
#include <iostream> #include <string> #include <vector> #include <array> using namespace std;class Solution{ public:int breathe; // 氣int count; //int result[2]; // 結果,活子個數,0白子,1黑子// 函數四:查看棋盤void watch(vector<vector<int>> &arr){for (int i = 0; i < arr.size(); i++){for (int j = 0; j < arr[i].size(); j++){cout << arr[i][j] << " ";}cout << endl;}}// 函數三:找到arr里面的值為a的數替換為b,并return a的數目int change(vector<vector<int>> &arr, int a, int b){int changeNum = 0;for (int i = 0; i < arr.size(); i++){for (int j = 0; j < arr[i].size(); j++){if (arr[i][j] == a) {arr[i][j] = b;changeNum++;}}}return changeNum;}// 函數一:遍歷所有棋子void solve(vector<vector<int>> &arr){breathe = 0;count = 0;result[0] = 0; // 活白子結果result[1] = 0;for (int i = 0; i < arr.size(); i++){for (int j = 0; j < arr[i].size(); j++){// 遍歷到已經處理過的子和空。矩陣0代表遍歷過,1代表為無子if (arr[i][j] == 0 || arr[i][j] == 1) continue;// 遍歷到白子,找到所有與之相連的子、氣if (arr[i][j] == 2){deepFirst(arr, 2, i, j);watch(arr);breathe = change(arr, -1, 1); // 回溯if (breathe >= 2){result[0] += count;}breathe = 0; // 回溯count = 0;}// 遍歷到黑子,找到所有與之相連的子、氣if (arr[i][j] == 3){deepFirst(arr, 3, i, j);watch(arr);breathe = change(arr, -1, 1); // 回溯if (breathe >= 2){result[1] += count;}breathe = 0; // 回溯count = 0;}}}}// 函數二:①找氣 ②找相連的相同子,處理過的子置為0// 子狀態,空為1,數過的空為-1,處理過黑白子置為0,黑子3,白子2void deepFirst(vector<vector<int>> &arr, int type, int i, int j){// 該子越界if (i < 0 || i >= arr.size() || j < 0 || j >= arr[0].size()) return; // 該子為1,空if (arr[i][j] == 1){ arr[i][j] = -1;return;}// 該子不匹配else if (arr[i][j] != type) {return;}// 該子為相連的子count++;arr[i][j] = 0;// 遞歸deepFirst(arr, type, i + 1, j);deepFirst(arr, type, i - 1, j);deepFirst(arr, type, i, j+1);deepFirst(arr, type, i, j-1);} };int main(){int N = 5;vector<vector<int>> arr = {{ 1, 1, 2, 3, 2, 3 },{ 3, 3, 2, 3, 3, 3 },{ 2, 2, 2, 3, 3, 3 },{ 1, 2, 2, 2, 3, 3 },{ 2, 1, 1, 2, 3, 1 }};Solution solution;solution.solve(arr);cout << solution.result[0] << " " << solution.result[1];while (1);return 0; }總結
以上是生活随笔為你收集整理的简化的围棋棋子规则(C++实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅析:如何选择关键词
- 下一篇: 科普了解高级编程语言的发展历程