文章目录
二维数组映射一维数组
所有的索引都是从(0, 0)开始的,将二维的坐标映射到一维
(2, 1) --> 2 *列数+1
(x, y) --> x *列数+y
一维数组映射二维数组
假设列数有13列,求一维数组索引为27的数映射到二维数组中的位置
27-->行索引: 27/13=2
-->列索引: 27%13=1
v-->行索引: v/列数
-->列索引: v%列数
四联通
设立4*2的二维数组directions,数字代表相对于当前坐标的位移。
第一维代表纵向,第二维代表横向。
向上和左均为负方向。向下和右均为负方向。
dirs = [[-1,0],
[0,1],
[1,0],
[0,-1]]
dirs = [ 上 , 右 , 左 , 下 ]
(0,0) | (0,1)| (0,2)
(1,0) |(1,1)| (1,2)
(2,0) |(2,1)| (2,2)
//对于x和y,d代表directions里的行数
for(d=0; d<4: d++){
next_x = x + dirs[d][0];
next_y = y + dirs[d][1];
...
}
例题-力扣695. 岛屿的最大面积
C++ - 不创建图
class Solution {
public:
const vector<vector<int>> dirs = {
{
-1, 0}, {
1, 0}, {
0, -1}, {
0, 1}};
//设置变量记录整个图的陆地最大面积
int res = 0;
//全局变量当前联通分量的最大陆地面积
int count = 0;
//设置访问数组
vector<vector<int>> visited;
int maxAreaOfIsland(vector<vector<int>>& grid) {
//定义并计算图的行数和列数
int row = grid.size(), col = grid[0].size();
//初始化visited数组
visited.assign(row, vector<int>(col, 0));
//遍历地图
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
//如果当前节点是陆地并且没有被访问过
if (grid[i][j] && !visited[i][j]) {
//当前联通分量的最大陆地面积
count = 0; //每个联通分量重新计数,并跟全局的最大面积作比较
dfs(grid, row, col, i, j);
if (count > res) res = count;
}
}
}
return res;
}
void dfs(vector<vector<int>>& grid, int row, int col, int i, int j) {
count++; //陆地面积+1
visited[i][j] = 1;
for (auto dir : dirs) {
int x = i + dir[0];
int y = j + dir[1];
if (x >= 0 && x < row && y >= 0 && y < col && grid[x][y] && !visited[x][y]) {
dfs(grid, row, col, x, y);
}
}
}
};
Java - 创建图,dfs的时候只需要传入顶点
// Java-Leetcode 695
import java.util.HashSet;
class Solution {
private int[][] dirs = {
{
-1, 0}, {
0, 1}, {
1, 0}, {
0, -1}};
private int R, C; //计算行数和列数
private int

最低0.47元/天 解锁文章
90

被折叠的 条评论
为什么被折叠?



