看华为面试题有一个,判断五子棋谁赢, bfs,记录一下,看不到样例,也不知道通不通过,
自己写的一个输入样例
输入 棋盘大小N=10, 1表示白旗,2表示黑棋,0表示空白位置。
10
1111100000
0120000000
0012000000
0001200000
0000020000
0000000000
0000000000
0000000000
0000000000
0000000000
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n;
vector<string> v;
int dx[] = {-1, -1, 0, 1, 1, 1, 0, -1}, dy[] = {0, 1, 1, 1, 0, -1, -1, -1};
int bfs(int x, int y)
{
if (v[x][y] - '0' == 0) return 0;
char kind = v[x][y]; // 1 表示白, 2表示黑;
//记录2个值,方向上旗子的个数,当前走的8个方向;
int dir_num[4] = {1, 1, 1, 1};
int mp[n][n];
memset(mp, -1, sizeof mp);
queue<pair<int, int>> q;
q.push(make_pair(x, y));
while (q.size())
{
auto t = q.front();
q.pop();
int _x = t.first, _y = t.second;
if (_x == x && _y == y)
{
for (int i = 0; i < 8; i ++ )
{
int a = _x + dx[i], b = _y + dy[i];
if (a >= 0 && a < n && b >= 0 && b < n && v[a][b] == kind)
{
q.push(make_pair(a, b));
mp[a][b] = i;
}
}
}
else
{
if(v[_x][_y] == kind)
{
dir_num[mp[_x][_y] % 4] += 1;
int a = _x + dx[mp[_x][_y]], b = _y + dy[mp[_x][_y]];
if (dir_num[mp[_x][_y] % 4] == 5) return (kind - '0');
else if (a >= 0 && a < n && b >= 0 && b < n && v[a][b] == kind)
{
q.push(make_pair(a, b));
mp[a][b] = mp[_x][_y];
}
}
}
}
return 0;
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ )
{
string s;
cin >> s;
v.push_back(s);
}
int flag = 1;
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < n; j ++ )
{
int num = bfs(i, j);
if (num == 1)
{
cout << "white" << endl;
flag = 0;
break;
}
else if (num == 2)
{
cout << "black" << endl;
flag = 0;
break;
}
}
if (!flag) break;
}
if (flag) cout << "none" << endl;
return 0;
}
------更新ACWING学习的方法----
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n;
vector<string> v;
int dx[] = {-1, -1, 0, 1}, dy[] = {0, 1, 1, 1};
int bfs(int x, int y)
{
if (v[x][y] - '0' == 0) return 0;
char kind = v[x][y];
for (int i = 0; i < 4; i ++ )
{
int l = 0, r = 0;
while (true)
{
int a = x + dx[i] * (r + 1), b = y + dy[i] * (r + 1);
if (a < 0 || a >= n || b < 0 || b >= n) break;
if (v[a][b] != kind) break;
r ++ ;
}
while (true)
{
int a = x - dx[i] * (l + 1), b = y - dy[i] * (l + 1);
if (a < 0 || a >= n || b < 0 || b >= n) break;
if (v[a][b] != kind) break;
l ++ ;
}
if (l + r + 1 == 5) return kind - '0';
}
return 0;
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ )
{
string s;
cin >> s;
v.push_back(s);
}
int flag = 1;
for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < n; j ++ )
{
int num = bfs(i, j);
if (num == 1)
{
cout << "white" << endl;
flag = 0;
break;
}
else if (num == 2)
{
cout << "black" << endl;
flag = 0;
break;
}
}
if (!flag) break;
}
if (flag) cout << "none" << endl;
return 0;
}-
杂题选讲
https://www.acwing.com/activity/content/problem/content/1814/1/
看到了,谢谢