-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path200.cpp
More file actions
49 lines (45 loc) · 1.1 KB
/
200.cpp
File metadata and controls
49 lines (45 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// 200.cpp
// LeetCode
//
// Created by 张佐玮 on 15/8/8.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Number of Islands
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int count = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j] == '1') {
count++;
markIsland(grid, i, j);
}
}
}
return count;
}
void markIsland(vector<vector<char>> &grid, int row, int col) {
if (grid[row][col] != '1') {
return;
}
grid[row][col] = '0';
if (row > 0) {
markIsland(grid, row - 1, col);
}
if (row < grid.size() - 1) {
markIsland(grid, row + 1, col);
}
if (col > 0) {
markIsland(grid, row, col - 1);
}
if (col < grid[0].size() - 1) {
markIsland(grid, row, col + 1);
}
}
};