在网格中寻找加号的算法
Algorithm for finding a plus sign in a grid
我有在给定网格中找到最大'PLUS'的问题。例如,如果我有以下网格:
..#..
..#.#
#####
..#.#
..#..
其中最大的加号大小为3。类似地,对于
..#
#.#
#.#
答案是1,因为没有特定的"PLUS"存在(当然除了原点)。
我想到的算法是这样的:
- 找到
#
和#
在其所有4个方向的位置。如图1中的(2, 2)
。 - 使用宽度优先搜索策略将其所有邻居连同它们所在的方向(左,右,上,下)添加到队列中。
- 继续访问并添加与该特定方向相关的邻居。
- 重复直到遇到
.
或跑出边界。
在做这些操作时,我们可以维护一个数组,该数组可以维护#
在每个方向上发生的计数。
int x[4] = {-1,0,1,0} ;
int y[4] = {0,1,0,-1} ;
int n, dir[4], result ;
char adj[2001][2001] ;
int bfs(int sx, int sy) {
queue < pair <int, pair <int, int> > > q ;
q.push(make_pair(0, make_pair(sx+x[0], sy+y[0]))) ;
q.push(make_pair(1, make_pair(sx+x[1], sy+y[1]))) ;
q.push(make_pair(2, make_pair(sx+x[2], sy+y[2]))) ;
q.push(make_pair(3, make_pair(sx+x[3], sy+y[3]))) ;
while (!q.empty()) {
pair <int, pair <int, int> > curr = q.front() ;
q.pop() ;
int current_direction = curr.first ;
int current_x = curr.second.first + x[current_direction] ;
int current_y = curr.second.second + y[current_direction] ;
if (current_x>=0&¤t_x<n&¤t_y>=0&¤t_y<n) {
if (adj[current_x][current_y] == '#') {
++dir[current_direction] ;
q.push(make_pair(current_direction, make_pair(current_x, current_y))) ;
}
else
break ;
}
else
break ;
}
result = *min_element(dir, dir+4) ;
return result ;
}
int main() {
int t ; scanf("%d", &t) ;
while (t--) {
scanf("%d", &n) ;
for (int i = 0; i < n; i++)
cin >> adj[i] ;
bool flag = true ;
int max_plus = 0 ;
for (int i = 1; i < n - 1; i++)
for (int j = 1; j < n - 1; j++) {
if (adj[i][j] == '#' && adj[i-1][j] == '#' \
&& adj[i][j+1] == '#' && adj[i+1][j] == '#' \
&& adj[i][j-1] == '#') {
// cout << i << " " << j << endl ;
flag = false ;
memset(dir, 2, sizeof(dir)) ;
max_plus = max(max_plus, bfs(i, j)) ;
}
}
if(flag)
cout << "1" << endl ;
else
cout << max_plus << endl ;
}
return 0 ;
}
对于图1,这段代码给出了一个奇怪的输出(33686019
)。我似乎找不到我在代码方面遇到的错误。此外,如果有什么问题的算法我有,我喜欢一些建议。
我不知道你的代码有什么问题,你的算法是否正确。但我不认为你需要BFS来解决这个问题。创建4个矩阵,保持每个#
的上下左右连续#
的数量:
..#..
..#.#
#####
..#.#
..#..
..0..
..1.0
00201
..3.2
..4..
下..4..
..3.2
00201
..1.0
..0..
..0..
..0.0
43210
..0.0
..0..
左..0..
..0.0
01234
..0.0
..0..
现在通过为每个元素保持最少4个矩阵来创建矩阵
最小值..0..
..0.0
00200
..0.0
..0..
答案是min
矩阵的最大值。
假设你想计算每个"#"后面有多少个连续的"#"。
for i from 0 to str.length
if s[i]=='#':
if s[i-1]=='#': // beware of i==0
dp[i] = dp[i-1]+1
else
dp[i] = 0
str ..##.###...##...
dp ..01.012...01...
相关文章:
- 寻找一种单一的定时方法来测试各种算法,不包括它们的输入
- 算法寻找功率,即n^p
- 在两个方向上寻找搜索算法 - c / c ++ / awk
- 摩尔投票算法寻找多数元素
- 在正方形矩阵中,每个单元格都是黑色或白色.设计了一个算法来寻找最大白色子平方
- 正在寻找元组替换算法
- 寻找 C4.5 算法的C++实现
- 寻找更高效的位域解码算法
- 寻找用于生成标准PRBS序列的*通用*算法
- 从函数中寻找最小值的启发式算法
- 寻找沿球面不与具有特定半径的其他球面相交的点的算法
- 使用BFS算法寻找最短路径
- 寻找匹配元素的算法
- 加速算法在两个2D点数据集中寻找最接近的项
- 如何应用泛洪算法寻找一个加权二维矩阵在指定的源和目的位置之间的最优路径
- 寻找单图像HDR算法
- 寻找重叠矩形算法
- 一种寻找图中无边指向外的内部连通节点簇的算法
- 在网格中寻找加号的算法
- 寻找容器中最现值的算法