Island Perimeter (上)

二维向量输入与初始化
本文介绍了如何在C++中正确地对二维向量进行输入和初始化,避免常见错误,并提供了一个示例程序来演示正确的操作流程。

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.


先查怎么赋初值:http://blog.youkuaiyun.com/u013068755/article/details/70198924

今天笔试的时候浪费了很长时间在一个很小的知识点上,导致笔试有一道题没有AC,非常气愤!引以为戒~

二维向量的输入问题:
不像二维数组那样,可以直接对arr[i][j]进行循环赋值。在vector<vector<int>>中,因为vector是一个容器,最外层的vector容器中放着更小的vector,而里层的vector里面放的是int型的数字。所以我们首先要对里层的vector容器赋值,然后再把里层的vector作为元素插入到外层的vector中。代码如下:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<vector<int>> test;
    vector<int> v;
    int n,temp;

    cin >> n;
    test.clear();

    //输入
    for (int i = 0; i<n; i++) {
        v.clear(); //每次记得clear:)
        for (int j = 0; j < n; j++)
        {
            cin >> temp;
            v.push_back(temp);
        }
        test.push_back(v);
    }

    //输出
    for(int i = 0; i < n; i++)
    {
        for(int j = 0;j < n; j++)
        {
            cout << test[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

自己先试试:


#include <iostream>
#include <vector>

using namespace std;

int islandPerimeter(vector<vector<int>>& grid) {
		int g = grid[1][2];
		int p = grid[0][1];
		int q = grid[3][3];
		printf("g=%d\np=%d\nq=%d\n", g,p,q);
		return  g;
                   };
int main()
{
	vector<vector<int>> test;
	vector<int> v;
	int n, temp;

	cin >> n;
	test.clear();

	//输入
	for (int i = 0; i<n; i++) {
		v.clear(); //每次记得clear:)
		for (int j = 0; j < n; j++)
		{
			cin >> temp;
			v.push_back(temp);
		}
		test.push_back(v);
	}

	//输出
	/*for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			cout << test[i][j] << " ";
		}
		cout << endl;
	}*/
	islandPerimeter (test);
	return 0;
}

结果:



赋初值不错!!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值